Replace first occurance of a word

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
danthemightyone
Forum Newbie
Posts: 4
Joined: Sun Dec 03, 2006 4:42 pm

Replace first occurance of a word

Post by danthemightyone »

Hi,
I have one small problem, I want to replace the first occurance of a word with another word.
I use replace function with regex expression \bword\b to find the word when it is not part of another word, however it replaces every occurrence of the word when I just want to replace the first occurrence.

Oh yea one other thing, I would like to replace a word beside a full stop '. '(This works fine) However if the word is part of a link eg. http://www.word.com then the word gets gets replaced. Surely I can put some check to prevent this from getting replaced?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

For the first problem, use the limit argument in preg_replace().

For the second problem, I would imagine that \sword\b would probably work better: there must be whitespace before the word (most words are like that, although the parentheses may be a little tricky). You could also do something really complicated as doing lookahead/behind assertions to ensure it's not a URLs, but it's really a question of functionality versus simplicity.
danthemightyone
Forum Newbie
Posts: 4
Joined: Sun Dec 03, 2006 4:42 pm

Post by danthemightyone »

Thanks that works,
one problem though with using \s before the word, if the word is the first word in the string then it will not be recognised.

One other thing, if in the string I am checking the word is found in an anchor tag eg. I am looking for 'word'

Here is a string and I am looking for <a href="#">a word in an <\a> anchor tag.

Can I use lookahead/behind assertions eg. for look ahead, if an opening anchor tag is found <a before a closing tag <\a then the word is out side the tag. If when looking ahead a closing anchor tag is found </a before an opening tag <a then the word is inside the tag.
How would this work?
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Post by GeertDD »

danthemightyone wrote:Thanks that works,
one problem though with using \s before the word, if the word is the first word in the string then it will not be recognised.
Use (^|\s)word\b
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

For your second question, at this point, it gets a little complicated, and you're probably better off parsing the HTML with DOM and then doing the processing by iterating through all the nodes until you get to a link, and then grab the word (searching recursively if necessary).
Post Reply