Page 1 of 1

help with a regular expression

Posted: Tue Mar 14, 2006 6:21 am
by jasongr
Hello

I am given a string
I would like to know if the string is of the form:
A, B and C
or
A,B, and C

where A B or C are any strings (not containing , but may contain whitespaces)
multiple whitespaces should be handled as well

For example:
"Me, you and some one else"
or
"Dogs, Cats, and horses"

I would to use regular expressions to catch both version, and if the string match the patterns
to obtain the 3 parts (A, B and C) into PHP variables, or into an array
where:
$arr[0] will hold A
$arr[1] will hold B
$arr[2 will hold C

If the string doesn't match either of the patterns, I need to know this

any help would be appreciated
thanks in advance

Posted: Tue Mar 14, 2006 10:00 am
by feyd
what have you come up with so far in regards to an expression?

Posted: Tue Mar 14, 2006 10:26 am
by jasongr
I got the following good solution from SKDevelopment:

Code: Select all

if(preg_match("/^\s*(\S.*?)\s*,\s*(\S.*?)\s*,\s*and\s*(.*)$/",$str,$m)) 
{ 
echo "<pre>"; print_r($m); echo "</pre>"; 
} 
elseif(preg_match("/^\s*(\S.*?)\s*,\s*(\S.*?)\s*and\s*(.*)$/",$str,$m)) 
{ 
echo "<pre>"; print_r($m); echo "</pre>"; 
} 
else 
echo "regular expression did not match";