【问题标题】:Replacing anchor href value with regex用正则表达式替换锚href值
【发布时间】:2014-11-16 20:37:41
【问题描述】:

我正在尝试通过在 href 值之前添加我的网站的 url 来替换网页中锚元素的所有 href 值。

在您建议 XML/HTML 解析器之前,请知道我尝试了其中的一堆,并且它们做得很好,但是对于我尝试解析的某些网站来说,它们都返回的 HTML 简直是一团糟。这可能与首先编写的损坏的 html 有关,但由于我无法控制它,因此正则表达式是这里唯一的方法。所以我想出了这个代码:

$response = '<h2><a href="http://www.google.com/test">Link</a></h2>';
$pattern = "/(<a .*?href=\"|')([^\"'#]+)(.*?<\/a>)/i";
$response = preg_replace_callback($pattern, 'html_href',  $response);
function html_href($matches) {
    return  $matches[1] . "http://example.com/" . $matches[2] .  $matches[3];
}

它实际上将$response 更改为:

<h2><a href="http://example.com/http://www.google.com/test">Link</a></h2>

太好了。但后来我发现这个正则表达式也匹配这个:

$response = "var href = $(this).attr('rel'); $(this).replaceWith('<a href=\"' + decodeURL(href) + '\"><span>' + anchor+ '</span></a>');";
$pattern = "/(<a .*?href=\"|')([^\"'#]+)(.*?<\/a>)/i";
$response = preg_replace_callback($pattern, 'html_href',  $response);
function html_href($matches) {
        return  $matches[1] . "http://example.com/" . $matches[2] .  $matches[3];
 }

这里 $response 变成:

var href = $(this).attr('http://example.com/rel'); $(this).replaceWith('<a href="' + decodeURL(href) + '"><span>' + anchor+ '</span></a>');

我不太明白,这个里面的attr()方法怎么会匹配替换呢?这个正则表达式模式不应该只匹配以 &lt;a 开头的字符串的一部分吗?我想避免匹配 javascript 中的内容...

【问题讨论】:

  • 交替管道| 在你的正则表达式中做什么?使用更多否定字符类来约束匹配上下文。
  • 管道应该匹配双引号或单引号,但可能我弄错了。你能举个例子,你会改变什么?
  • (&lt;a .*?href=\"|') 表示&lt;a .*?href=\"'

标签: php regex


【解决方案1】:

只是一些常见的方法:

  • 首选&lt;a\s+而不是&lt;a␣

  • 此后使用[^&lt;&gt;]* 而不是.*? 进行标签内属性跳过。 (这可能是它在其他地方超匹配 JavaScript 的主要原因。)

  • 当您想允许 "' 使用字符类 [\"\'] 时,就像您在中间所做的那样。

  • 例如,更严格地匹配 href= 内容与 ([^&lt;\"\'&gt;]+)

  • 然后确保随后出现另一个[\"\']

  • 并用[^&lt;&gt;]*&gt; 断言&lt;a 标记的结尾(这可能是不匹配所需标记/链接的另一个主要原因)。

再次使用[^&lt;&gt;]+ 作为链接文本,如果这与您的输入html 一致的话。 专业提示:尽可能以崇高的/x 表示法编写此类正则表达式模式。

【讨论】:

    【解决方案2】:

    试试这个

    PHP

    $re = "/(<a.*href=)[\"'](.*)[\"']/m";
    $str = "<h2><a href=\"http://www.google.com/test\">Link</a></h2>2014-54-22 22:23";
    $subst = "\1\"http://example.com/\2\"";
    
    $result = preg_replace($re, $subst, $str);
    

    live demo

    【讨论】:

    • 如何处理特定的url,我该怎么做,意味着在添加example.com后从google.com中删除http://
    猜你喜欢
    • 2011-04-19
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多