php - PHP preg_replace:用正则表达式将文本中的所有锚标记替换为它们的 href 值
问题描述
我想用它们的 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>"));
推荐阅读
- python - 我可以改变什么来让 k-means 以 Python 中预期的方式对我的数据进行聚类?
- android - 无法读取 packageName ':generateDebugBuildConfig'
- javascript - 如果在从数据库中获取数据后选中一个复选框,如何禁用其他复选框
- r - 如何为带有左对齐和右对齐文本的绘图添加标题
- c# - 对其中包含 Environment.Exit() 调用的方法进行单元测试
- swift - 我收到此错误“尝试将非属性列表对象设置为 NSUserDefaults”
- office365 - 客户端应用程序是否必须注册 Azure AD 才能访问 Microsoft Graph API?
- python - 如何使用python检查[dot]文件夹是否存在
- ios - 带有函数参数的 CoreData 谓词
- javascript - 如何在chart.js上设置正确的时间刻度X轴每小时刻度