Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top