【发布时间】:2023-03-31 20:35:02
【问题描述】:
我想用它们的 href 值替换文本中的所有锚标记,但我的模式不能正常工作。
$str = 'This is a text with multiple anchor tags. This is the first one: <a href="https://www.link1.com/" title="Link 1">Link 1</a> and this one the second: <a href="https://www.link2.com/" title="Link 2">Link 2</a> after that a lot of other text. And here the 3rd one: <a href="https://www.link3.com/" title="Link 3">Link 3</a> Some other text.';
$test = preg_replace("/<a\s.+href=['|\"]([^\"\']*)['|\"].*>[^<]*<\/a>/i",'\1', $str);
echo $test;
最后的文字应该是这样的:
This is a text with multiple anchor tags. This is the first one: https://www.link1.com/ and this one the second: https://www.link2.com/ after that a lot of other text. And here the 3rd one: https://www.link3.com/ Some other text.
非常感谢!
【问题讨论】:
-
你真的想试试parse HTML with RegEx ...你确定吗?您是否首先在办公桌周围画了一个五角星以防万一?
-
@CD001 如果有更好、更简单的解决方案,我将不胜感激。
-
更安全的是使用 DOM Parser; HTML 不是正则的,因此尝试使用正则表达式解析它通常会导致问题 - 这几乎就是我发布的链接所指出的......但有更多的风格、类和幽默;)
标签: php regex preg-replace