Page 1 of 1
Whats wrong with this regex -- parsing city province???
Posted: Tue Jul 14, 2009 2:07 pm
by alex.barylski
Code: Select all
preg_split('#(\W+)\([A-Z]{2}\)#', $subject);
Basically I am passing it input in the form:
Code: Select all
Winnipeg (MB)
Regina (SK)
Toronto (ON)
You see the pattern I'm sure...I want two parameters back, first being the city (with possible white space), the second being the province abbreviation wrapped in round brakctes with a single space between them and the city name.
Obviously the regex I have written does not work, it only matches the city and ignores the province...
Re: Whats wrong with this regex -- parsing city province???
Posted: Tue Jul 14, 2009 2:16 pm
by pickle
Why are you using preg_split()? preg_match() would seem to be a better fit.
\W won't work well - what about "Trois Rivieres" or "Flin Flon", only the first word would be found.
Use this:
/(.*?) \((.*)\)/
Re: Whats wrong with this regex -- parsing city province???
Posted: Tue Jul 14, 2009 2:23 pm
by prometheuzz
pickle wrote:Why are you using preg_split()? preg_match() would seem to be a better fit.
...
Possibly, unless he wants to get the two parts (city & province) back separated, then split is appropriate here.
@PCSpectra, you could split on the white space that has a '(' in front of it:
Code: Select all
print_r(preg_split('/\s(?=\()/', 'Trois Rivieres (AB)'));
/*
Array
(
[0] => Trois Rivieres
[1] => (AB)
)
*/
Re: Whats wrong with this regex -- parsing city province???
Posted: Tue Jul 14, 2009 2:30 pm
by alex.barylski
Thanks to both of you, I have tried the latter example:
Code: Select all
$search_region = preg_split('#/\s(?=\()/#', $request->search_region, null, PREG_SPLIT_DELIM_CAPTURE);
Still getting the result:
Any ideas? Not all city names will have spaces, but some will most definetely.
Re: Whats wrong with this regex -- parsing city province???
Posted: Tue Jul 14, 2009 2:41 pm
by prometheuzz
It works fine:
Code: Select all
print_r(preg_split('/\s(?=\()/', 'Winnipeg (MB)'));
/*
Array
(
[0] => Winnipeg
[1] => (MB)
)
*/
Re: Whats wrong with this regex -- parsing city province???
Posted: Tue Jul 14, 2009 2:59 pm
by alex.barylski
I copied your code verbatim and that seems to have fixed the issue, thanks a bunch

Re: Whats wrong with this regex -- parsing city province???
Posted: Tue Jul 14, 2009 3:04 pm
by prometheuzz
PCSpectra wrote:I copied your code verbatim and that seems to have fixed the issue, ...
But you see the difference, right? You're using double delimiters (both '/' and '#') while only one is needed.
PCSpectra wrote:... thanks a bunch

You're welcome.