带边界查询的正则表达式

I am finding certain words in my data and replacing those keywords with anchor tags.

eg. keyword: disney

data:

This is temp data -disney-movie-deaths.html nightmare some more text disney This is some more data.

I want to convert this as:

This is temp data -disney-movie-deaths.html nightmare some more text <a href="/test.php">disney</a> This is some more 

I have used regx as: /\bdisney\b/i

But problem is that it is converting it as:

This is temp data -<a href="/test.php">disney</a>-movie-deaths.html nightmare some more text disney This is some more 

Can someone face this type of issue?

Your logic is sound, but word boundaries are not enough in your case. You see that \bdisney\b matches -disney- (Why shouldn't it?) For your example I added some spaces behind and after the word you are matching :

$result = preg_replace('/\s+(disney)\s+/', '<a href="/test.php">$1</a>', $subject);

While this will work for this example it may also not be enough. For example it will not work with disney. You can modify it according to your needs.

You want to make sure that disney is a word by itself. Here's the regex that I used:

[\s\.]disney[\s\.$]

here's how I tested it:

http://rubular.com/r/YyZMeGITJY

Use \s instead of \b

/\sdisney\s/i

\b means word boundary and includes "-" as matching character

http://www.regular-expressions.info/wordboundaries.html

I think this might work:

preg_replace("#(?:\s|\A)(disney)(?:\s|\z)#m", "<a>\1</a>", $text);