I was wondering: how would I change all occurrences of a certain word in a HTML, but only outside of tags?
Example:
Lets say I want to replace all occurrences of myWordToReplace
with <a href="#">myWordToReplace</a>
So this html
<p data-something="myWordToReplace"> myWordToReplace andSomeOtherText</p>
should yield
<p data-something="myWordToReplace"> <a href="#">myWordToReplace</a> andSomeOtherText</p>
I was trying to achieve this with regex, but it's also a mess - I thought perhaps a DOM parser would do the trick? Any help appreciated?
EDIT: @Muhammet's answer will do the trick if all your text is wrapped in some tags - but if parts of your text are without a tag, that text will not be replaced of course. I'm now trying to achieve this too.
Example: if I want to change myWord
to someOtherWord
:
Nam myWord pharetra <strong>auctor myWord</strong>
Should yield
Nam someOtherWord pharetra <strong>auctor someOtherWord </strong>
but now it only changes the second word - the one inside strong tags.
This is working great for me. I don't know why it doesn't take the "data-something", it seems that it doesn't like the dash between the two words. But as it works, I hope it is useful for you.
I am using Simple HTML DOM Library
You could do something like this
Here is another DOM-based solution to wrap parts of text nodes into
<a>
tags (usingsearch
as a sample):Here is an IDEONE demo