
提取 html 标签属性:正则表达式的巧妙应用
在处理 html 标签时,提取特定的属性至关重要。本问答将指导您使用正则表达式从 html 标签中捕获常用的属性值。
正则表达式方案:
$re = '/\bon\w+=([\'"]).*?\1/m';
解释:
立即学习“前端免费学习笔记(深入)”;
替换策略:
$subst = '';
对于每个匹配,我们将其替换为空字符串,从而仅保留属性名称。
使用示例:
$str = '<strong style="white-space: normal;" class="123" onload="asdasdas()">12313123 </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>'; $result = preg_replace($re, $subst, $str); echo "替换的结果是 " . $result;
结果:
替换的结果是 <strong class="123">12313123 </strong><div class="ccc">aaaaa</div> <p style="white-space: normal;">bbbbb</p> <strong class="123">12313123 </strong> <strong >eeeeee </strong><a class="aaaa">链接链接</a><p>ffff</p>
如您所见,此解决方案有效地从 html 标签中提取了您指定的属性(style、class、href、target、alt),而无需其他不需要的部分(例如事件处理程序)。
以上就是如何用正则表达式高效提取HTML标签属性?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号