2

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.

André Silva
  • 1,110
  • 8
  • 24

1 Answers1

3

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    The only scenario I was missing was that it can be only `.popup` which doesn't work with this regex because I'm specifically saying that it has to be followed by either space, dot or {. Either way, I slightly changed your answer into `/\.popup((?=[\s\.{])|\z)/` – André Silva Sep 22 '16 at 11:00