【问题标题】:How to remove all links from a string that does not have an absolute link?如何从没有绝对链接的字符串中删除所有链接?
【发布时间】:2023-01-10 15:47:48
【问题描述】:

我有一个包含文本和一些链接的字符串。我想删除所有没有绝对链接但保留其文本的链接。

我想用正则表达式而不是加载 dom 来做。

那可能吗?

我试过这个正则表达式

preg_replace('#href=["\']([^/][^\':"]*)["\']#', $root_path.'$1', $html);

但这只会用空字符串替换 href。

我想完全删除锚标记并仅保留其文本。

【问题讨论】:

  • 因此,例如,如果 HTML 是 Hello <a href="https://www.example.com">world!</a>,输出应该是 Hello world!
  • 不, href 在这种情况下是绝对的,所以它应该保持原样。如果 href 是相对 URL 那么是的,它应该从世界中删除链接!。

标签: php regex


【解决方案1】:

您可以为此尝试使用preg_replace_callback

这是一个这样做的例子

$string = "This is a test string with a non-absolute link: 
www.example.com and an absolute link: https://www.example.com";

$string = preg_replace_callback("/(?!http(s?)://)(www.[S]+)/i",
 function($matches) {
    return $matches[0];
 }, $string);

echo $string;

希望对您有所帮助。

【讨论】:

  • 你提供一个JS代码?
  • 您更新后的答案会将链接替换为空字符串,而不是锚文本?
  • 我已经编辑了我的代码
  • 这仍然显示链接而不是仅显示锚文本。
【解决方案2】:

您可以使用此正则表达式,但要谨慎对待!它远非完美,所以请针对您的用例尝试一下,如果出现任何问题,请在评论中写下,我会尝试为您修复正则表达式!

<?php

$re = '/<a(s+[w-]+?(=(['"].*?['"])|([wd]+?))?)*s+href=['"](?!https?://)(?<link>[^'"]+?)['"](s+[w-]+?(=(['"].*?['"])|([wd]+?))?)*>(?<text>.+?)</a>/m';
$str = '<a class="aaa" href="/example" data-enabled>Hello</a> <a href="https://www.example.com">world!</a>';

$string = '<a href="/example">Hello</a> <a href="https://www.example.com">world!</a>';

$out = preg_replace_callback($re,
 function($matches) {
    return $matches['text'];
 }, $string);
 
var_dump($out);

【讨论】:

    猜你喜欢
    • 2013-06-03
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多