12

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.

2 Answers 2

30

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks; I should RTFM before asking next time.
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... ;)
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 ;)
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.
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.