PHP – preg_replace back reference (in replacement text) examples

Sometimes we need to use back reference in PHP preg_replace to put back the matched pattern. One example can be if you want to append certain string after the pattern. Here are few examples.

preg_replace back reference using back slash

Replace hello with hello-2 (when followed by world) and preserve case. We’ll use \1 to back reference first parenthesis match in replacement text.

<?php
$str = "hello world. Hello world";
$newstr = preg_replace('/(hello)/i', '\1-2', $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):
hello-2 world. Hello-2 world
Env: PHP version 5.5.9 (Linux)

Note that you can use \0 for the full pattern match.

preg_replace back reference using ${1}

Replace hello with hello-2 (when followed by world) and preserve case. We’ll use ${1} to back reference first parenthesis match in replacement text. This approach works better if ${1} is immediately followed by an alphanumeric character in replacement text.

<?php
$str = "hello world. Hello world";
$newstr = preg_replace('/(hello)/i', '${1}-2', $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):
hello-2 world. Hello-2 world
Env: PHP version 5.5.9 (Linux)

Note that you can use ${0} for the full pattern match.

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

Comments

Click here to write/view comments