![](/img/trans.png)
[英]PHP preg_replace: Replace all anchor tags in text with their href value with Regex
[英]Replacing anchor href value with regex
我试图通过在href值之前添加网站的网址来替换网页中锚元素的所有href值。
在您建议XML / HTML解析器之前,请知道我尝试了很多,但它们都做得很好,但是它们全部返回的HTML只是弄乱了我要解析的某些网站。 这可能与最初编写的损坏的html有关,但是由于我对此没有控制权,因此regex是唯一的方法。 所以我想出了这段代码:
$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\\s+
而不是<a␣
此后使用[^<>]*
代替.*?
标签内属性跳过。 (这可能是它与其他地方的JavaScript完美匹配的主要原因。)
当您想允许"
或'
使用字符类[\\"\\']
,就像在中间一样。
例如,将href =内容更严格地与([^<\\"\\'>]+)
匹配。
然后确保随后出现另一个[\\"\\']
。
并用[^<>]*>
声明<a
标签的[^<>]*>
(这可能是导致与所需标签/链接不匹配的另一个主要原因)。
如果连贯地适合您输入的html,请再次使用[^<>]+
作为链接文本。 提示:请尽可能以高大的/x
表示法编写此类正则表达式模式。
尝试这个
的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.