2015-06-03 65 views
0

替换文本到URL我有一些变量:如何从段落

$string = 'he says of stackoverflow.com, & http://google.com, the website he founded in 2001' 
$string = 'he says of www.stackoverflow.com & http://www.google.com the website he founded in 2001' 

现在我想用URL的更换给HTML链接

我使用的preg_replace funtion:

echo preg_replace("#http://([\S]+?)#Uis", '<a href="http://\\1">\\1</a>', $string2); 

此代码仅将http://-url替换为链接。
此外,如果有后.COM逗号(例如像http://google.com,),这个逗号的需求是在链接,以及:<a href="http://www.google.com,">

请告诉我,我怎么可能archieve这一点。

+0

你确定你想要的逗号是URL的一部分?通常它应该是_excluded_,就像一个尾随点(就像在正常的写作语言中一样,你可以附加一个逗号或一个点作为交互作用,而不是URL的一部分)。 – giorgio

+0

preg_replace已经转换并在com后使用逗号,但我不想转换逗号 –

回答

0

你需要增强你的正则表达式来匹配没有http://和www的url。以及。然而,仍然存在问题,因为区分包含来自有效URL的点的任意字符序列是复杂的。

下面的模式应该适合你的需求:

(?:https?:\/\/)?((?:www\.)?([\w\.\-]){2,}\.[a-z,]{2,5}(:?\?[\w=#,-]+)?) 

http://regexr.com/3b4ov