PHP regex – word boundary examples

Php regex can use word boundary character (\b) to match a word boundary. Beginning of string if following by a word character will also match word boundary. Similarly end of string will also match a word boundary if immediately preceded by a word character (alphanumeric or underscore).

preg_match word boundary positive example

<?php
if (preg_match('/\bfoo\b/i', "foobar foo", $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 (at offset 7)
Env: PHP version 5.5.9 (Linux)

preg_match word boundary negative example

<?php
if (preg_match('/\bfoo\b/i', "foobar foo_bar", $matches, PREG_OFFSET_CAPTURE)) {
  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
  echo "No match\n";
}
?>
No match
Env: PHP version 5.5.9 (Linux)

Note that underscore (_) is not considered as word boundary.

preg_replace word boundary example

<?php
$str = "foo bar foo-bar foobar foo";
$newstr = preg_replace('/\bfoo\b/i', 'NEWVAL', $str, -1, $count);
if ($count > 0) {
  echo "newstr after $count replacement(s):\n$newstr\n";
} else {
  echo "No replacement\n";
}
?>
newstr after 3 replacement(s):
NEWVAL bar NEWVAL-bar foobar NEWVAL
Env: PHP version 5.5.9 (Linux)

Note that dash (-) is considered as word boundary.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments