【问题标题】:Remove nested links in a text using regex/php使用 regex/php 删除文本中的嵌套链接
【发布时间】:2019-07-17 10:55:40
【问题描述】:

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

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

例子:

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

【问题讨论】:

  • 你尝试了什么正则表达式?你完成了什么?您是否尝试过使用 regex101.com ?请记住,stackoverflow 是为了帮助您解决问题,而不是为您编写代码。
  • 我已经用我一直在尝试的最后一段代码编辑了这个问题,

标签: php html regex


【解决方案1】:

您可以使用以下内容:

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

我希望这会有所帮助。

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

【讨论】:

【解决方案2】:

我终于这样解决了

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

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

感谢您的提示 Mohammad Bagheri。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多