Understanding Pattern in preg_match_all() Function Call

Kevin_TA picture Kevin_TA · Jan 8, 2012 · Viewed 9.6k times · Source

I am trying to understand how preg_match_all() works and when looking at the documentation on the php.net site, I see some examples but am baffled by the strings sent as the pattern parameter. Is there a really thorough, clear explanation out there? For example, I don't understand what the pattern in this example means:

preg_match_all("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
            "Call 555-1212 or 1-800-555-1212", $phones);

or this:

$html = "<b>bold text</b><a href=howdy.html>click me</a>";
preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

I've taken an introductory class on PHP, but never saw anything like this. Some clarification would be appreciated.

Thanks!

Answer

deceze picture deceze · Jan 8, 2012

Those aren't "PHP patterns", those are Regular Expressions. Instead of trying to explain what has been explained before a thousand times in this answer, I'll point you to http://regular-expressions.info for information and tutorials.