使用 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);
}

您可以使用以下内容:

$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);

我希望这有所帮助。

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

最后我以这种方式解决了

    $pattern = '/<a.*>([a-zA-Z0-9&#;s]*<a.*>[a-zA-Z0-9&#;s]*</a>[a-zA-Z0-9&#;s]*)</a>/m';
preg_match_all($pattern, $text, $matches, PREG_SET_ORDER, 0);
foreach($matches as $match)
{
    $text = str_replace($match[1], strip_tags($match[1]), $text);
}
return $text;

老实说,我不认为这是最好的方法,但是在大多数情况下它有效。

感谢您的提示穆罕默德·巴盖里。

最新更新