preg_replace仅在文本上而不在href内部

时间:2010-10-21 16:16:10

标签: php regex

我有这个代码在html内容上做一些丑陋的内联文本样式颜色格式。 但这会打破标签内的任何内容,如链接和电子邮件。

我已经想到了如何防止它格式化链接,但是当文本是info@mytext.com

时它仍然无法阻止替换
$text = preg_replace('/(?<!\.)mytext(?!\/)/', '<span style="color:#DD1E32">my</span><span style="color:#002d6a">text</span>', $text);

什么是更好的方法来只替换文本,并阻止替换链接?

3 个答案:

答案 0 :(得分:1)

更好的方法是使用XML函数。

答案 1 :(得分:0)

你的lookbehind断言只测试一个字符,所以它不足以在html标签之外断言匹配。这是正则表达式不是最佳选择的地方。然而,您可以获得如下近似值:

preg_replace("/(>[^<]*)(?<![@.])(mytext)/", "$1<span>$2</span>",

如果没有html标签,则会忽略mytext的第一个隐藏。因此,$text = "<div>$text</div>"或其他内容效果最佳。

答案 2 :(得分:0)

[编辑]哦,我看到你解决了href问题。 要解决您的电子邮件问题,请更改所有@mytext。在处理文本之前,使用str_replace [email_safeguard],完成后,将其更改回来。 :)

$text = str_replace('info@mytext.com','[email_safeguard]',$text); 
//work on the text with preg_match()
$text = str_replace('[email_safeguard]','info@mytext.com',$text); 

应该这样做:)

但正如人们之前提到的,你最好避免使用html和正则表达式,否则你将遭受克苏鲁的愤怒。

see this instead