PHP beginning and end of string regex examples

Php regex can use caret (^) for matching from beginning of string and dollar ($) for end of line. Here are some examples using preg_replace. Similar regex can be used with preg_match also.

preg_replace beginning of string match example

Replace hello with NEWVAL if it occurs in the beginning.

<?php
$str = "hello world. hello world2";
$newstr = preg_replace('/^hello/', 'NEWVAL', $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):
NEWVAL world. hello world2
Env: PHP version 5.5.9 (Linux)

preg_replace beginning of string or preceded by space match

Replace hello with NEWVAL if it occurs in the beginning of is preceded by space.

<?php
$str = "hello world. hello world2. ahello world3";
$newstr = preg_replace('/(^hello|\shello)/', 'NEWVAL', $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):
NEWVAL world.NEWVAL world2. ahello world3
Env: PHP version 5.5.9 (Linux)

preg_replace end of string match example

Replace world (with NEWVAL) if it occurs in the end.

<?php
$str = "hello world. hello world";
$newstr = preg_replace('/world$/', 'NEWVAL', $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):
hello world. hello NEWVAL
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