PHP - 在字符串中添加指向 URL 的链接(如果不存在)


PHP - Add link to a URL in a string if not present

假设我有一个字符串,如$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);
}

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

谢谢。

好吧,我只是将您的后视路径修改为(?<!href="|">)以避免标签内的链接......

所以使用:

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

正则表达式 101 演示

代码板演示