首页 > 文章列表 > PHP正则表达式如何提取HTML标签指定属性并忽略其他属性?

PHP正则表达式如何提取HTML标签指定属性并忽略其他属性?

374 2025-03-16

PHP正则表达式如何提取HTML标签指定属性并忽略其他属性?

php正则表达式过滤html标签属性

问题提出:

求教如何在 php 中使用正则表达式提取 html 标签的指定属性,例如 style、class、href、target、alt,而忽略其他属性。

解决方案:

可以使用以下正则表达式匹配事件处理程序属性(例如 onload="asdasdas()"):

/on.*?=/

然后使用 preg_replace() 函数替换匹配项:

$re = '/bonw+=(['"]).*?1/m';

其中:

  • /m 修饰符允许正则表达式匹配多行文本。
  • 1 引用项用于匹配开头引号和结尾引号之间捕获的内容。

代码示例:

$re = '/bonw+=(['"]).*?1/m';
$str = '<strong style="white-space: normal;" class="123" onload="asdasdas()">&nbsp</strong><div class="ccc">aaaaa</div>
<p style="white-space: normal;">bbbbb</p>
<strong class="123" style="white-space: normal;" onload="asdasdas()">12313123&nbsp</strong>
<strong onload='asdasdas()'">eeeeee&nbsp</strong><a href="http://www.xxx.com" target="_blank" class="aaaa">链接链接</a><p>ffff</p>';
$subst = '';

$result = preg_replace($re, $subst, $str);

echo "替换的结果是 ".$result;
来源:1733097154