Search code examples
phpregexpreg-replacepreg-replace-callback

PHP regular expressions - Replacing one backreference


Is there a way in preg_replace() or preg_replace_callback() to replace only one backreference? For instance I have this regular expression: /(\.popup)([\s\.{])/ and this string .popup .popup-option. The backreferences that will be generated are as follows: $0 = .popup\s, $1 = .popup, $2 = \s. I want to replace only the $1 by another string. How do I manage to do this?

Thanks.


Solution

  • You can use preg_replace_callback like this:

    $s = '.popup .popup-option'; // original string
    
    echo preg_replace_callback('/(\.popup)([\s\.{])/', function ($m) {
        return 'foo' . $m[2]; }, $s);
    //=> foo .popup-option
    

    In the callback we are returning some replacement string foo concatenated with $m[2] thus getting only $m[1] replaced.


    Do note that using lookahead you can do the same in preg_replace:

    echo preg_replace('/\.popup(?=[\s\.{])/', 'foo', $s);
    //=> foo .popup-option