Naif Posted June 27, 2009 Share Posted June 27, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/163868-limit-word-boundary-search-in-preg_replace/ Share on other sites More sharing options...
.josh Posted June 27, 2009 Share Posted June 27, 2009 lookup negative lookaround Quote Link to comment https://forums.phpfreaks.com/topic/163868-limit-word-boundary-search-in-preg_replace/#findComment-864637 Share on other sites More sharing options...
thebadbad Posted June 27, 2009 Share Posted June 27, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/163868-limit-word-boundary-search-in-preg_replace/#findComment-864644 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.