Preg_replace: add number after trackback

Situation

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

Example

from

 abcdefghij 

to

 a8bcde8fghi8j 


Question

How to write a replacement string?

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

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

+7
php regex escaping backreference
source share
2 answers

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

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

which will output a8bcde8fghi8j

See the manual in this special case with backlinks.

+18
source share

You can do it:

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

Here is the relevant quote from the documentation regarding the backlink:

When working with a replacement pattern, when reverse replication immediately follows a different number (for example: placing a literal number immediately after the matched pattern), you cannot use the familiar \ 1 notation for your backlink. \ 11, for example, will confuse preg_replace () since it does not know if you want 1 1 backlink followed by literal 1, or \ 11 backreference, and then nothing. In this case, the solution should use \ $ {1} 1. This creates an isolated backward link for $ 1, leaving 1 as a literal.

+4
source share

All Articles