php正则表达式之常见html标签处理

后端开发PHP 476

移除html字符串中的超链接

两种情况,一种仅移除<a>标签,保留标签里面的文本

$yourcodewithlinks = 'i am a <a href="#">link</a>!';
$yourcodewithoutlinks = preg_replace('/<a href=\"(.*?)\">(.*?)<\/a>/', "\\2", $yourcodewithlinks);
echo $yourcodewithoutlinks;

使用时需要注意,原文本字符中单引号和双引号的区分,

$yourcodewithlinks = 'i am a <a href="#">link</a>!'

$yourcodewithlinks = "i am a <a href='#'>link</a>!"

这两种情况是不一样的,需要在正则表达式中修改。

另一种情况是移除<a>和</a>之间所有内容

$content = preg_replace("/<a href=.*?>(.*?)<\/a>/","",$content);

移除style标签

$output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $input);

Post Comment