
php正则表达式过滤html标签属性
问题提出:
求教如何在 php 中使用正则表达式提取 html 标签的指定属性,例如 style、class、href、target、alt,而忽略其他属性。
解决方案:
立即学习“PHP免费学习笔记(深入)”;
可以使用以下正则表达式匹配事件处理程序属性(例如 onload="asdasdas()"):
/on.*?=/
然后使用 preg_replace() 函数替换匹配项:
$re = '/\bon\w+=([\'"]).*?\1/m';
其中:
- /m 修饰符允许正则表达式匹配多行文本。
- 1 引用项用于匹配开头引号和结尾引号之间捕获的内容。
代码示例:
$re = '/\bon\w+=([\'"]).*?\1/m'; $str = '<strong style="white-space: normal;" class="123" onload="asdasdas()"> </strong><div class="ccc">aaaaa</div> <p style="white-space: normal;">bbbbb</p> <strong class="123" style="white-space: normal;" onload="asdasdas()">12313123 </strong> <strong onload=\'asdasdas()\'">eeeeee </strong><a href="http://www.xxx.com" target="_blank" class="aaaa">链接链接</a><p>ffff</p>'; $subst = ''; $result = preg_replace($re, $subst, $str); echo "替换的结果是 ".$result;











