1

With preg_replace, I can replace a matched substring by another like this :

echo preg_replace("yellow", "blue", "sky is yellow");
// print "sky is blue"

But is it possible to replace only a substring in the search string by another string ?

By example, I would like change this text :

<a>foo</a>
<a class="changehere">foo</a>
<a>foo</a>

by

<a>foo</a>
<a class="changehere">FAA</a>
<a>foo</a>

I tried this :

echo preg_replace("@<a class="changehere">(foo)</a>@", "FAA", $text);

But the whole of the line is changed to FAA ... How can I find a substring, depending of others char around, and replace only the substring ?

Thanks for help :) ! I Hope I'm clear

spacecodeur
  • 2,206
  • 7
  • 35
  • 71

1 Answers1

1

Assuming you're not parsing HTML/XML using regex, you may use this regex:

php > $text = '<a class="changehere">FAA</a>';
php > echo preg_replace('@<a class="changehere">\Kfoo(?=</a>)@', "FAA", $text);
<a class="changehere">FAA</a>

Details:

  • \K: resets all matched info
  • (?=</a>): Lookahead to assert we have </a> ahead of current position
anubhava
  • 761,203
  • 64
  • 569
  • 643