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.
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:
- /foo\/bar/
- #/foo/bar/#
- %foo/bar%
- |foo/bar|
- ~foo/bar~
- {foo/bar}
- [foo/bar]
- <foo/bar>
- (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 7.4.33 (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 7.4.33 (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 7.4.33 (Linux)