繁体   English   中英

PHP preg_replace:用正则表达式将文本中的所有锚标记替换为它们的 href 值

[英]PHP preg_replace: Replace all anchor tags in text with their href value with Regex

我想用它们的 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.

非常感谢你!

只是不要。

改用解析器。

$dom = new DOMDocument();
// since you have a fragment, wrap it in a <body>
$dom->loadHTML("<body>".$str."</body>");
$links = $dom->getElementsByTagName("a");
while($link = $links[0]) {
    $link->parentNode->insertBefore(new DOMText($link->getAttribute("href")),$link);
    $link->parentNode->removeChild($link);
}
$result = $dom->saveHTML($dom->getElementsByTagName("body")[0]);
// remove <body>..</body> wrapper
$output = substr($result, strlen("<body>"), -strlen("</body>"));

3v4l 演示

也许不是更简单,但更安全的是用 strpos 循环字符串以查找和剪切字符串并删除 html。

$str = 'This is a text with multiple anchor tags. This is the first one: <a class="funky-style" 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.';

$pos = strpos($str, '<a');

while($pos !== false){
    // Find start of html and remove up to link (<a href=")
    $str = substr($str, 0, $pos) . substr($str, strpos($str, 'href="', $pos)+6);
    // Find end of link and remove that.(" title="Link 1">Link 1</a>)
    $str = substr($str, 0, strpos($str,'"', $pos)) . substr($str, strpos($str, '</a>', $pos)+4);
    // Find next link if possible
    $pos = strpos($str, '<a');
}
echo $str;

https://3v4l.org/vdN7E

编辑以处理 a 标签的不同顺序。

如果您仍然使用正则表达式,这应该有效:

preg_replace("/<a\s+href=['\"]([^'\"]+)['\"][^\>]*>[^<]+<\/a>/i",'$1', $str);

但是使用 Andreas 发布的解决方案可能会更好。

仅供参考:您之前的正则表达式不起作用的原因是这个小数字:

.*>

因为. 选择您最终匹配要替换的 url 之后的所有内容; 一直到最后。 这就是为什么它似乎只选择并替换它找到的第一个锚标签并切断其余的。

将其更改为

[^\>]*

确保此特定选择仅限于存在于 url 和 a 标记的结束括号之间的字符串部分。

如果你想用 href 值替换标签,你可以这样做:

$post = preg_replace("/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/","$1",$post);

如果要替换为文本值:

$post = preg_replace("/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/","$2",$post);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM