【发布时间】: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()方法怎么会匹配替换呢?这个正则表达式模式不应该只匹配以 <a 开头的字符串的一部分吗?我想避免匹配 javascript 中的内容...
【问题讨论】:
-
交替管道
|在你的正则表达式中做什么?使用更多否定字符类来约束匹配上下文。 -
管道应该匹配双引号或单引号,但可能我弄错了。你能举个例子,你会改变什么?
-
(<a .*?href=\"|')表示<a .*?href=\"或'。