Php regex delimiter examples

PHP requires regex patterns to have valid delimiters around it. Some languages may not require delimiters (e.g. python). To make code more readable, sometimes we want to use different delimiters. This article will list some commonly used delimiters.

php-regex-delimiters

List of commonly used php regex delimiters

Any non-alphanumeric, non-backslash, non-whitespace character can be used as pattern delimiter in PCRE regular expressions. Here are some commonly used delimiters:

  1. /foo\/bar/
  2. #/foo/bar/#
  3. %foo/bar%
  4. |foo/bar|
  5. ~foo/bar~
  6. {foo/bar}
  7. [foo/bar]
  8. <foo/bar>
  9. (foo/bar)

Since brackets are frequently used in regular expressions, using other delimiters makes code more readable. I prefer using slash or hash.

Some preg_match and preg_replace regex delimiter examples

preg_match using slash (/) as delimiter

<?php
if (preg_match('/foo\/bar/', "abc/foo/bar/def", $matches, PREG_OFFSET_CAPTURE)) {
  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
  echo "No match\n";
}
?>
matched string:
foo/bar (at offset 4)
Env: PHP version 5.5.9 (Linux)

preg_match using hash (#) as delimiter

<?php
if (preg_match('#foo/bar#', "abc/foo/bar/def", $matches, PREG_OFFSET_CAPTURE)) {
  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
  echo "No match\n";
}
?>
matched string:
foo/bar (at offset 4)
Env: PHP version 5.5.9 (Linux)

preg_replace using percent (%) as delimiter

<?php
$str = "abc/foo/bar/def";
$newstr = preg_replace('%foo/bar%', '_foo_/_bar_', $str, -1, $count);
if ($count > 0) {
  echo "newstr after $count replacement(s):\n$newstr\n";
} else {
  echo "No replacement\n";
}
?>
newstr after 1 replacement(s):
abc/_foo_/_bar_/def
Env: PHP version 5.5.9 (Linux)
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments