2015-06-03 68 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