Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.