繁体   English   中英

PHP preg_replace正则表达式排除html <a>标记</a>

[英]PHP preg_replace regex exclude html <a> tag

目标是:我有一些头衔。 我想将标题转换为文本链接。 但是当它是一个链接时,我不想更改。 我正在寻找正确的正则表达式。

我有这样的PHP代码:

foreach($res as $r) {
  $new_string = '<a href="#" onclick="getMarkers(1,\\\' \\\',1);locate('.$r->latitude.','.$r->longitude.','.$r->zoom.','.$r->id.',0);">$0</a>';
  $introduction = (preg_replace("/\b$r->title\b(?![^<>]*(?:<|$))/i",$new_string,$introduction))
}

我的代码的这一部分不起作用:

preg_replace("/\b$r->title\b(?![^<>]*(?:<|$))/i",$new_string,$introduction)

问题是:此正则表达式还更改了HTML标记中的可用链接。

谢谢大家耐心等待,我在等待答案!

谢谢!


更新 :我要感谢HamZa这个出色的链接!

 $introduction = (preg_replace("/[^>]*>.*?<\/a>(*SKIP)(*FAIL)|$r->title/im",$new_string,$introduction));

谢谢大家! :)

这可能是一个过分简单的解决方案,但是您可以在后面使用否定式确保该URL前面没有href= 如果不是,则使用您喜欢的任何REGEX域捕获它。

我使用了一个笨拙的域名验证器,因此看起来一团糟,但我将对其进行解释。

$string = 'This is just a bunch of random text. <A HREF="http://www.google.com">google</A> This is 
just a bunch of random text. http://www.yahoo.com This is just a bunch of random text. 
<A HREF="http://www.cnn.com">cnn.com</A> This is just a bunch of random text. http://www.msn.com This 
is just a bunch of random text. ';

$string = preg_replace('~(?<!href="|href=\'|href=)((?:http(?:s)?://)(?:www\.)?[-A-Z0-9.]+(?:\.[-A-Z0-9]{2,4})[-A-Z0-9_./]?(?:[-A-Z0-9#?/]+)?)~i', '<a href="$1">$1</a>', $string);

print $string;

输出:

This is just a bunch of random text. <A HREF="http://www.google.com">google</A> This is 
just a bunch of random text. <a href="http://www.yahoo.com">http://www.yahoo.com</a> This is just a bunch of random text. 
<A HREF="http://www.cnn.com">cnn.com</A> This is just a bunch of random text. <a href="http://www.msn.com">http://www.msn.com</a> This 
is just a bunch of random text.

好的,现在解释一下REGEX:

(?<!href="|href=\'|href=)    ((?:http(?:s)?://)(?:www\.)?[-A-Z0-9.]+(?:\.[-A-Z0-9]{2,4})[-A-Z0-9_./]?(?:[-A-Z0-9#?/]+)?)
              ^                                                ^
              1                                                2

实际上只有两部分:

  1. 这是一个否定性的隐喻,可确保该URL前面没有href="href=' (当然是转义的)或href=
  2. 下一部分只是一个域验证脚本。 如果愿意,可以在这里使用更简单的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM