help with a regular expression

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

help with a regular expression

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

what have you come up with so far in regards to an expression?
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post 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";
Post Reply