Examples

Example 1-13. Simple match

//Find Spider-Man, Spiderman, SPIDER-MAN, etc.
$dailybugle = "Spider-Man Menaces City!";

$regex = "/spider[- ]?man/i";

if (preg_match($regex, $dailybugle)) {
      //do something
}

Example 1-14. Match and capture group

//Match dates formatted like MM/DD/YYYY, MM-DD-YY,...
$date = "12/30/1969";
$p    = "!^(\\d\\d)[-/](\\d\\d)[-/](\\d\\d(?:\\d\\d)?)$!";

if (preg_match($p,$date,$matches) {
      $month = $matches[1];
      $day   = $matches[2];
      $year  = $matches[3];
}

Example 1-15. Simple substitution

//Convert <br> to <br /> for XHTML compliance
$text = "Hello world. <br>";

$pattern  = "{<br>}i";

echo preg_replace($pattern, "<br />", $text);

Example 1-16. Harder substitution

//urlify - turn URLs into HTML links
$text = "Check the web site, http://www.oreilly.com/catalog/regexppr.";
$regex =
        "{ \\b                      # start at word\n"
     .  "                           # boundary\n"
     .  "(                          # capture to $1\n"
     .  "(https?|telnet|gopher|file|wais|ftp) : \n"
     .  "                           # resource and colon\n"
     .  "[\\w/\\#~:.?+=&%@!\\-]+?   # one or more valid\n"
     .  "                           # characters\n"
     .  "                           # but take as little as\n"
     .  "                           # possible\n"
     .  ")\n"
     .  "(?=                        # lookahead\n"
     .  "[.:?\\-]*                  # for possible punct\n"
     .  "(?:[^\\w/\\#~:.?+=&%@!\\-] # invalid character\n"
     .  "|$)                        # or end of string\n"
     .  ") }x";


echo preg_replace($regex, "<a href=\"$1\">$1</a>", $text);

Get Regular Expression Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.