使用regex/php删除文本中的嵌套链接
我有一些有很多链接的文本,其中一些有嵌套链接。我试图创建一个正则表达式来删除链接锚中留下锚文本的任何链接 我的想法是使用regex查找所有文本锚,并用相同的文本替换它们,同时删除标记。但是我不能做到 例如:使用regex/php删除文本中的嵌套链接,php,html,regex,Php,Html,Regex,我有一些有很多链接的文本,其中一些有嵌套链接。我试图创建一个正则表达式来删除链接锚中留下锚文本的任何链接 我的想法是使用regex查找所有文本锚,并用相同的文本替换它们,同时删除标记。但是我不能做到 例如: <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 <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-zA-Z].*)/”;
preg_match_all($pattern,$text,$matches);
foreach($matches作为$match进行匹配)
{
$text=str_replace($match[0],strip_标记($match[0],“”),$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='/更多文本。;
preg_match_all($pattern,$text,$matches,preg_SET_ORDER,0);
$matches=$matches[0];
$to_search=$matches[1];
未设置($matches[0],$matches[1]);
$to_replace='';
foreach($matches作为$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;
$pattern='/([a-zA-Z0-9\s]*[a-zA-Z0-9\s]*[a-zA-Z0-9\s]*]m';
preg_match_all($pattern,$text,$matches,preg_SET_ORDER,0);
foreach($matches作为$match进行匹配)
{
$text=str_replace($match[1],strip_标记($match[1]),$text);
}
返回$text;
老实说,我不认为这是最好的方法,但它在大多数情况下都有效
感谢您的提示Mohammad Bagheri。您尝试了什么正则表达式?你完成了什么?你试过使用regex101.com吗?请记住,stackoverflow在这里是为了帮助您解决问题,而不是为您编写代码。我已经用我尝试的最后一段代码编辑了这个问题,感谢您的halp,但它只是在示例中起作用,如果文本有更多链接,它就有问题。例如,此文本:任何文本或更多文本。其他