Reputation: 49441
I have the following code:
function mmh_links($message){
ini_set('auto_detect_line_endings','1');
$row = 1;
if (($handle = fopen(realpath(dirname(__FILE__))."/mmh_replace.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$message = preg_replace("/({$data[0]}(?![^><]*?(?:>|<\/a)))/i","<a href=\"{$data[1]}\" class=\"postlink\">$1</a>",$message,1);
}
fclose($handle);
}
return $message;
}
Which looks for specific keywords from a CSV file and surround them by a link given in the CSV file as well. Additionally, it makes sure it only replaces each keyword only once, and makes sure it doesn't replace keywords that are already within links, and it is case insensitive. All good so far.
Now I want to limit to search to "whole words", meaning I don't want "test" to catch "xxxtestxxx".
What's my best option to do this, while keeping all the rules I wrote before?
Upvotes: 4
Views: 3052
Reputation: 17781
Wrap the whole words you'd like to match with the \b
operator - this indicates a word boundary:
$pattern = "/(\b{$data[0]}\b(?![^><]*?(?:>|<\/a)))/i";
$subject = "<a href=\"{$data[1]}\" class=\"postlink\">$1</a>";
$message = preg_replace($pattern, $subject, $message, 1);
Upvotes: 4