Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

RegEx: matching a word not part of another one 1

Status
Not open for further replies.

c4n

Programmer
Mar 12, 2002
110
SI
Hello,

Here is what I want to do. I have this string for example:

$text="THIS bla blaTHIS bla THISbla THIS THIS";

Now what I'm trying to do is match only those "THIS" that are separate words and NOT part of other words and replace it with THAT. For example the above should become:

$text="THAT bla blaTHIS bla THISbla THAT THAT";

Get the idea? I only want to match those "THIS" that are a word by themselves and not a part of some other word. For example I would like to match "CAT" as a word but not "CAT" in "CATapult".

This is what I came up with so far:


$text = preg_replace("/(^|\s)THIS($|\s)/","$1THAT$2 ",$text);

It matches either beginning of string or space before THIS AND end of string or space after THIS

It seems to work fine except in cases when I have two "THIS THIS" next to each other. It works if I put two spaces between THIS ("THIS THIS") but not with a single space ("THIS THIS").

I'm not sure how to solve this so any suggestions welcome!
 
Do simply this?
[tt] $text = preg_replace("/\bTHIS\b/","THAT",$text);
[/tt]
 
Wow, how simple. I was complicating things too much because I didn't know of the \b for word boundary. Thanks, I learned a lot new today!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top