Regex OR (alternation) in php can be matched using pipe (|) match character. This is very frequently used in regular expressions. Following are some ways pipe can be used in php regex
(hello|foo|bar)will match any of hello, foo, bar(|foo|bar)will match foo or bar or nothing. It is equivalent to optional match(foo|bar)?(^|foo)will match either foo or beginning of string.(foo|$)will match either foo or end of string.
preg_match example for pattern (A|B|C)
PHP preg_match example which matches with hello or foo or bar with space in beginning and end (ignoring case)
<?php
if (preg_match('/ (hello|foo|bar) /i', "hello world. food bar and something", $matches, PREG_OFFSET_CAPTURE)) {
echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
echo "No match\n";
}
?>matched string: bar (at offset 17)
Env: PHP version 8.2.29 (Linux)
preg_replace example for pattern (^|A)
PHP preg_replace example which removes hello when preceded by space or is in beginning (ignoring case)
<?php
$str = "hello world. sayhello. hello world again";
$newstr = preg_replace('/(^| )hello/i', "", $str, -1, $count);
if ($count > 0) {
echo "newstr after $count replacement(s):\n$newstr\n";
} else {
echo "No replacement\n";
}
?>newstr after 2 replacement(s): world. sayhello. world again
Env: PHP version 8.2.29 (Linux)
preg_replace example for pattern (A|$)
PHP preg_replace example which removes hello when followed by space or is in end (ignoring case)
<?php
$str = "hello world. hellos last hello";
$newstr = preg_replace('/hello( |$)/i', "", $str, -1, $count);
if ($count > 0) {
echo "newstr after $count replacement(s):\n$newstr\n";
} else {
echo "No replacement\n";
}
?>newstr after 2 replacement(s): world. hellos last
Env: PHP version 8.2.29 (Linux)
Few points to note
- It is better to use brackets when using regex OR.
- Pipe can be escaped using backslash for its literal use (\|).