1

I am looking for a way to replace all the occurrences of specific word inside a pattern: for example:
I love my dog <a>the dog is a good dog, -dog and dog: also should be converted</a> with
I love my dog <a>the pig is a good pig, -pig and pig: also should be converted</a>

all the occurrences of dog inside the <a> tag should be replaced with pig.

I had tied the next preg_replece:
preg_replace("/<a>.*(dog).*</a>/", "pig", $input_lines); but I got empty string..

I would thankful for some help.

user2979757
  • 783
  • 2
  • 8
  • 12
  • You should either use another regex delimiter like `$` or escape the one you are using isnide `` because its breaking your regex, –  Nov 21 '13 at 16:46

2 Answers2

0

You can use:

$s = <<< EOF
I am looking for a way to replace all the occurrences of specific word dog inside a pattern: for example:
I love my dog <a>the dog is a good dog, -dog and dog: also should be converted</a> with
I love my dog <a>the pig is a good pig, -pig and pig: also should be converted</a>
not this dog.
EOF;
echo preg_replace_callback("~(<a>.*?</a>)~", function ($m) {
               return str_replace('dog', 'pig', $m[1]); }, $s);

OUTPUT:

I am looking for a way to replace all the occurrences of specific word dog inside a pattern: for example:
I love my dog <a>the pig is a good pig, -pig and pig: also should be converted</a> with
I love my dog <a>the pig is a good pig, -pig and pig: also should be converted</a>
not this dog.
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You can use a substitution with $1pig using this regex:

((?:<a>|\G(?<!^))(.*?))\bdog\b(?=.*?<\/a>)

Live DEMO

For a full explanation, please check THIS (I couldnt do better)

Community
  • 1
  • 1
Enissay
  • 4,969
  • 3
  • 29
  • 56