NYCPHP Meetup

NYPHP.org

[nycphp-talk] no tunderstanding preg_grep behavior

inforequest 1j0lkq002 at sneakemail.com
Sun May 21 22:16:22 EDT 2006


I have a string of html, and inside are a few phone numbers. I used preg_split to split the string into tags and their contents, and am using preg_grep on that array to find phone numbers. It works fine... except I don't understand why the results array from preg_grep is not just the matches but the entire array plus 2 more (the matches) (?).

I doubt I can recreate a decent regex inside this email, but basically it's just 

$mystring='
<strong>Exxon Mobil</strong><br>refinery inventory<br>empty orders<br>Verona, NJ 07044<br>973-432-0277<br>973-439-4877 (fax)<br>Washington Mutual Insurance<br>
';

//one line per tag or content
$pattern = '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/';
$html_array = preg_split ('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', trim ($mystring), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);


$phone = preg_grep("/^\D*(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$/", $html_array);

If you examine $phone, it has all of the html_array and then the twophonenumbers found, properly keyed. 

Thanks for helping me understand this. I expected thelength of $phone to be num_matches, and the first element to be the first phone number found.  Oops.

-=john andrews





More information about the talk mailing list