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
  • 703
  • 2
  • 8
  • 12
  • You should either use another regex delimiter like `$` or escape the one you are using isnide `` because its breaking your regex, – brezanac 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
  • 713,503
  • 59
  • 514
  • 593
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,874
  • 3
  • 27
  • 51