忽略preg_replace中的img标签 [英] Ignore img tags in preg_replace

查看:249
本文介绍了忽略preg_replace中的img标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换HTML字符串中的一个单词,但是如果该单词在'img'元素的属性中,我想排除该替换.

I want to replace a word in an HTML string, but I want to exclude the replacement if the word was in the attributes of the 'img' element.

示例:

$word = 'google';
$html = 'I like google and here is its logo <img src="images/google.png" alt="Image of google logo" />';

$replacement = '<a href="http://google.com">Google</a>';
$result =  preg_replace('/\s'.($word).'/u', $replacement, $html);

preg_replace还将替换'src'和'alt'属性内的"google"词,我希望它仅替换'img'元素外的词.

preg_replace will also replace the "google" words inside 'src' and 'alt' attributes, I want it to just replace the word outside the 'img' element.

推荐答案

您可以使用丢弃模式.例如,您可以使用如下正则表达式:

You can use the discard pattern. For instance you can use a regex like this:

<.*?google.*?\/>(*SKIP)(*FAIL)|google

工作演示

Working demo

此模式背后的想法是丢弃<>中的google单词,但保留其余部分:

The idea behind this pattern is to discard the google word inside < and > but keep the rest:

<.*?google.*?\/>(*SKIP)(*FAIL)  --> This part will skip the matches where google is within <...>
|google                         --> but will keep the others google

您可以添加所需的许多丢弃"模式,例如:

You can add many "discard" pattern you want, like:

discard patt1(*SKIP)(*FAIL)|discard patt(*SKIP)(*FAIL)|...(*SKIP)(*FAIL)|keep this

这篇关于忽略preg_replace中的img标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆