
php正则表达式过滤html标签属性
问题提出:
求教如何在 php 中使用正则表达式提取 html 标签的指定属性,例如 style、class、href、target、alt,而忽略其他属性。
解决方案:
立即学习“PHP免费学习笔记(深入)”;
可以使用以下正则表达式匹配事件处理程序属性(例如 onload="asdasdas()"):
/on.*?=/
然后使用 preg_replace() 函数替换匹配项:
$re = '/\bon\w+=([\'"]).*?\1/m';
其中:
代码示例:
$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;
以上就是PHP正则表达式如何提取HTML标签指定属性并忽略其他属性?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号