PHP – Regex OR (alternation) examples using pipe

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

  1. (hello|foo|bar) will match any of hello, foo, bar
  2. (|foo|bar) will match foo or bar or nothing. It is equivalent to optional match (foo|bar)?
  3. (^|foo) will match either foo or beginning of string.
  4. (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 5.5.9 (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 5.5.9 (Linux)
Note that hello in sayhello is not replaced here.

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 5.5.9 (Linux)
Note that hello in hellos is not replaced here.

Few points to note

  1. It is better to use brackets when using regex OR.
  2. Pipe can be escaped using backslash for its literal use (\|).
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments