8

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.

MightyPork
  • 16,661
  • 9
  • 66
  • 120

2 Answers2

24

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.

Aron Cederholm
  • 5,237
  • 4
  • 34
  • 53
  • 2
    Thanks; I should RTFM before asking next time. – MightyPork Aug 03 '13 at 00:01
  • Ok. Just promise to not give up on asking valid questions (like this one). We learn by questioning, and this time, I guess you got an answer 10x speedier than by trial-and-error. Someone is bound to know the solution... ;) – Aron Cederholm Aug 03 '13 at 00:04
  • As a matter of fact, after posting it I went to php.net, and *found the answer*. I was already writing own answer when you spared me the shame of answering it myself ;) – MightyPork Aug 03 '13 at 00:05
  • 3
    Note the single quotes. `"${1}8"` does not work, because double quoted strings are parsed/interpreted in php and therefore the braces "disappear" disappear before the string is passed to the function. – Mr Tsjolder Sep 22 '16 at 17:38
4

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.

jh314
  • 24,533
  • 14
  • 58
  • 79