首页 > 解决方案 > 使用 regex/php 删除文本中的嵌套链接

问题描述

我有一些带有很多链接的文本,其中一些有嵌套链接。我试图创建一个正则表达式来删除链接锚内的任何链接,留下锚文本。

我的想法是使用正则表达式来查找所有文本锚点,并将它们替换为相同的文本并删除标签。但是,我无法实现它。

例子:

<p>Any text <a href="#">a correct link</a> more text <a href="#">some <a href="#">word</a>.</a><p>

预期结果

<p>Any text <a href="#">a correct link</a> more text <a href="#">some word.</a><p>

我正在尝试的是它遵循的内容:

$pattern="/<a.*>([a-zA-Z ].*)<\/a>/";
preg_match_all ($pattern , $text, $matches);
foreach($matches as $match)
{
    $text=str_replace($match[0],strip_tags($match[0],'<b>'),$text);
}

标签: phphtmlregex

解决方案


您可以使用以下内容:

$pattern = '/<a.*>.*(<a.*>(.*)<\/a>(.*))<\/a>/m';
$text = '<p>Any text <a href="#">a correct link</a> more text <a href="#">some <a href="#">word</a>.</a><p>';

preg_match_all($pattern, $text, $matches, PREG_SET_ORDER, 0);

$matches = $matches[0];
$to_search = $matches[1];
unset($matches[0], $matches[1]);

$to_replace = '';
foreach($matches AS $match)
    $to_replace .= $match;

$str = str_replace($to_search, $to_replace, $text);

我希望这有帮助。

如果您需要更多帮助,请告诉我。


推荐阅读