Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace: add number after backreference

Situation

I want to use preg_replace() to add a digit '8' after each of [aeiou].

Example

from

abcdefghij

to

a8bcde8fghi8j


Question

How should I write the replacement string?

// input string
$in = 'abcdefghij';

// this obviously won't work ----------↓
$out = preg_replace( '/([aeiou])/', '\18',  $in);

This is just an example, so suggesting str_replace() is not a valid answer.
I want to know how to have number after backreference in the replacement string.

like image 397
MightyPork Avatar asked Aug 02 '13 23:08

MightyPork


2 Answers

The solution is to wrap the backreference in ${}.

$out = preg_replace( '/([aeiou])/', '${1}8',  $in);

which will output a8bcde8fghi8j

See the manual on this special case with backreferences.

like image 131
Aron Cederholm Avatar answered Sep 28 '22 00:09

Aron Cederholm


You can do this:

$out = preg_replace('/([aeiou])/', '${1}' . '8', $in);

Here is a relevant quote from the docs regarding backreference:

When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \1 notation for your backreference. \11, for example, would confuse preg_replace() since it does not know whether you want the \1 backreference followed by a literal 1, or the \11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

like image 28
jh314 Avatar answered Sep 28 '22 01:09

jh314