1

Im trying to implement functionality wich will replace only specific word between <p> tags

For example:

<p>this is word i need to replace</p>

In this case "word" will be replaced with some other word (but only inside <p> tags)

Currently im using:

preg_replace("/\b$keyword\b/", $replaceWord, $content, 2);

$content - contains all html
$keyword - word wich need to be replaced in that content
$replaceWord - word wich we want to use instead $keyword

But this logic above will replace also keywords wich are not inside paragraph. How its possible to update this regex, so it replaces only words inside paragraphs?

NOTE: Please make a note that i cannot use Simple HTML DOM Parser

cool
  • 3,225
  • 3
  • 33
  • 58

1 Answers1

-1

I'm not familiar w/ php, but here it is in python. Figured I'd try and help since you were unanswered for a while. You can see that I'm matching and storing the stuff surrounding the word, and adding that back in w/ my replacement called "new word". And that it does indeed ignore the word "word" inside the < h1 > tags.

>>> import re
>>> a = "<p>this is word i need to replace</p>"
>>> a += "\n<h1>blah blah crud word</h1>"
>>> re.sub("(<p>.*?)word(.*?</p>)","\g<1>new word\g<2>",a)
'<p>this is new word i need to replace</p>\n<h1>blah blah crud word</h1>'
pyInTheSky
  • 1,459
  • 1
  • 9
  • 24
  • 1
    Why would you think posting a Python answer for a PHP tagged question would be helpful to the OP? – kittycat Apr 19 '13 at 18:23
  • OP obviously knows how to use regex, their problem was a matter of figuring out how to 'word' the regex correctly. If I say you need to group the surrounding parts and do the replacement, that's all they need to know. Most languages are 90% the same, and most support a very similar set of functionality when it comes to regex. It's better than the 3 comments under the original question which amount to 'just do it our way, even if you may not be familiar with it, because we know exactly what you REALLY need'. – pyInTheSky Apr 19 '13 at 18:34