如何将文本从段落替换为URL

  • 本文关键字:替换 URL 段落 文本 php
  • 更新时间 :
  • 英文 :


我有一些变量:

$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函数:

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

此代码仅将http://-url's替换为链接。
此外,如果。com后面有一个逗号(例如http://google.com,),这个逗号也需要放在链接中:<a href="http://www.google.com,">

请告诉我如何存档。

您需要增强您的正则表达式模式匹配url没有http://和www。也然而,仍然存在一个问题,因为从有效的url中区分包含点的任意字符序列是很复杂的。

下面的模式应该满足您的需求:

(?:https?://)?((?:www.)?([w.-]){2,}.[a-z,]{2,5}(:??[w=#,-]+)?)
http://regexr.com/3b4ov

最新更新