【发布时间】:2021-03-26 11:27:15
【问题描述】:
我在变量中有 html 代码。例如$html 等于:
<div title="Cool stuff" alt="Cool stuff"><a title="another stuff">......</a></div>
我需要用title="$newTitle"替换所有标题属性title="Cool stuff"和title="anot stuff"等的内容。
有没有任何非正则表达式的方法来做到这一点?
如果我必须使用正则表达式,有没有比我想出的更好(性能方面)和/或更优雅的解决方案?
$html = '...'
$newTitle = 'My new title';
$matches = [];
preg_match_all(
'/title=(\"|\')([^\"\']{1,})(\"|\')/',
$html,
$matches
);
$attributeTitleValues = $matches[2];
foreach ($attributeTitleValues as $title)
{
$html = str_replace("title='{$title}'", "title='{$newTitle}'", $html);
$html = str_replace("title=\"{$title}\"", "title=\"{$newTitle}\"", $html);
}
【问题讨论】:
-
您应该使用
SimpleXMLElement()将html 转换为一个对象,这样您就可以在具有title="whatever"的节点上进行XPath。请参阅stackoverflow.com/a/65206705/2191572 以开始使用。 -
@MonkeyZeus 啊,我没有看到“这个答案的内容存在争议......”的横幅。当有人问到关于 Regex 和 HTML 的问题时,我已经多次看到这个答案了????
-
要获取所有带有标题的节点,可以使用
//*[@title] -
@MonkeyZeus 谢谢。这似乎是我正在寻找的那种解决方案。
-
我不能接受这是正确的答案,所以我会接受另一个(后来的)来结束这个。但是再次感谢您,
标签: php dom replace html-parsing