phpregexpreg-replacebackreferencecapture-group

Why are all backreferences in replacement string of preg_replace() empty?


What I'm doing wrong?

echo preg_replace('#\d{3}\d{3}\d{3}\d{2}#', '$1.$2.$3-$4', '12345678901');

Output should be this: 123.456.789-01, but I'm getting ..-.


Solution

  • <?php
    echo preg_replace('#(\d{3})(\d{3})(\d{3})(\d{2})#', '$1.$2.$3-$4', '12345678901');
    

    is correct, because dollar sign + integer refers to content in () brackets (grouping)

    demo