如何替换所有textlink并添加<a href=""> tag using php?

时间:2017-02-11 16:08:32

标签: php regex preg-replace

i want to add <a href=""> to all textlink which i missed add <a href=""> when i submit post.

Ex:

<a href"http://google.com">google.com</a> and https://paypal.com

And i just want to add <a href=""> for text https://paypal.com which i missed add <a href="">

Thanks!

1 个答案:

答案 0 :(得分:0)

使用preg_replace函数和负向lookbehind断言的解决方案

$str = '<a href="http://google.com">google.com</a> and https://paypal.com';
$result = preg_replace("/(?<![=\">])https?:\/\/([^\s]+)/", '<a href="$1">$1</a>', $str);

print_r($result);

输出(作为源代码):

<a href="http://google.com">google.com</a> and <a href="paypal.com">paypal.com</a>

(?<!=\") - 负面后瞻断言,确保匹配的网址不在属性分配前="