【问题标题】:PHP - Add link to a URL in a string if not presentPHP - 如果不存在,则在字符串中添加指向 URL 的链接
【发布时间】:2013-09-09 12:42:09
【问题描述】:

假设我有一个字符串,如 $str ::

$str = "Test,

Here\'s an interesting in-house litigation position with JPMorgan Chase in New York I thought you might be interested inL

<a href="http://www.example.com/lcdetail.php?akey=e1725">http://www.example.com/lcdetail.php?akey=e1725</a>

They are not using recruiters to fill this job, so if you are interested you can just apply directly.  

http://www.example.com/lcdetail.php?akey=e1725

Cordially
--Harrison";

现在我想给不存在标签的链接添加标签。

我使用了这个函数,但没有返回想要的值。

function processString($s){  
  return preg_replace('@(?<!href=")(https?:\/\/[\w\-\.!~?&=+\*\'(),\/]+)((?!\<\/\a\>).)*@i','<a href="$1">$1</a>',$s);
}

我的要求是不要在链接中添加锚标记(如果存在)并添加到那些没有的。

谢谢。

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    好吧,我刚刚将您的后向路径修改为 (?&lt;!href="|"&gt;) 以避免标签内的链接...

    所以使用:

    function processString($s){  
      return preg_replace('@(?<!href="|">)(https?:\/\/[\w\-\.!~?&=+\*\'(),\/]+)((?!\<\/\a\>).)*@i','<a href="$1">$1</a>',$s);
    }
    

    Regex101 Demo

    Codepad Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 2015-07-05
      • 1970-01-01
      相关资源
      最近更新 更多