繁体   English   中英

使用PHP从字符串中删除包含其内部文本的链接的正则表达式

[英]Regular expression to remove links with their inner text from a string with PHP

我有以下代码:

$string = 'Try to remove the link text from the content <a href="#">links in it</a> Try to remove the link text from the content <a href="#">testme</a> Try to remove the link text from the content';
$string = preg_replace('#(<a.*?>).*?(</a>)#', '$1$2', $string);
$result = preg_replace('/<a href="(.*?)">(.*?)<\/a>/', "\\2", $string);
echo $result; // this will output "I am a lot of text with links in it";

我正在寻找合并这些preg_replace行。 请提出建议。

您需要将DOM用于这些任务。 这是从您的内容中删除链接的示例:

$str = 'Try to remove the link text from the content <a href="#">links in it</a> Try to remove the link text from the content <a href="#">testme</a> Try to remove the link text from the content';
$dom = new DOMDocument;
@$dom->loadHTML($str, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
$xp = new DOMXPath($dom);
$links = $xp->query('//a');
foreach ($links as $link) {
    $link->parentNode->removeChild($link);
 }
echo preg_replace('/^<p>([^<>]*)<\/p>$/', '$1', @$dom->saveHTML());

由于文本节点是文档中唯一的文本节点,因此PHP DOM创建了一个虚拟p节点来包装文本,因此我正在使用preg_replace删除它。 我认为这不是你的情况。

IDEONE演示

暂无
暂无

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

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