Jump to content

Limit word boundary search in preg_replace


Naif

Recommended Posts

Hi,

 

I am trying to create a statement using preg_replace which searches for a word based on word boundary and the search is going to be case insensitive. The problem I am experiencing is that I need to ensure it doesn't search for this word inside an <img /> tag. So basically I need to restrict the search from being performed inside <img />. The code I am using at the moment is as follows:

 

$content = preg_replace("/\b$key\b/i", "<u>\\0</u>", $content);

 

I'll appreciate the help that I can get here. Thanks.

 

Regards,

-- Naif

The pattern shouldn't match the keyword inside any HTML tag, right? Here's a pattern that avoids that:

 

<?php
$content = 'Paragraph with a keyword and keywords. Then a image tag <img src="/path/keyword/image.png" />';
$key = 'keyword';
$content = preg_replace('~\b' . preg_quote($key, '~') . '\b(?![^<]*?>)~i', '<u>$0</u>', $content);
echo $content;
?>

Output:

Paragraph with a <u>keyword</u> and keywords. Then a image tag <img src="/path/keyword/image.png" />

 

I've explained the pattern in an earlier post. It's also a good idea to run any external input through preg_quote(), in case a special character needs to be escaped.

 

I'd also recommend to use e.g. <span style="text-decoration: underline;">keyword</span> instead of <u>keyword</u>, since <u> is deprecated.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.