Search code examples
phpreplacepreg-replace

preg_replace add "00" after $1 without spaces in Replacement


Im trying to add "00" after $1 without spaces in preg_replace replacement.

My code:

$count = null;
$returnValue = preg_replace('/de(.*)y/i', '$1 00', 'delipsumy', -1, $count);

I want have something like '$1'.'00' for the replacement where the output should be:

lipsum00 (without any space)

I already tried something like '$1'.'00' and '$100' but doesnt work

Any suggestion?


Solution

  • This is addressed in the method's documentation (emphasis added):

    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.

    So your replacement pattern would be '\${1}00'. So as an example:

    // Output: H__e__ll__o__ W__o__rld
    echo preg_replace("/([aeiou])/", "__\${1}__", "Hello World");
    

    See it in action: http://codepad.org/orbK5jdw