2015-11-19 45 views
2

我想要的網址鏈接轉換成字符串轉換的URL鏈接字符串中的使用的preg_replace()

我有以下字符串:

$x="Welcome to my [homepage](http://example.com) ,Please check our [About us](http://example.com/about-us) page for more info about this site. 

我想在心裏[轉換並]鏈接標題和一切內部(和)href屬性值:

歡迎來到我的homepage,請檢查我們的About us頁面有關本網站的更多信息。

我試圖的preg_replace()函數,但它不工作

$x="Welcome to my [homepage](http://example.com) ,Please check our [About us](http://example.com/about-us) page for more info about this site"; 

echo preg_replace("/\[([^\]+)\]\(([^\)]+)\)/i","<a href='$2'>$1</a>",$x); 

我得到的輸出相同的字符串:

Welcome to my [homepage](http://example.com) ,Please check our [About us](http://example.com/about-us) page for more info about this site. 

是什麼錯我的代碼?

請幫忙!

+0

你輸入的字符串的樣子降價。你有沒有考慮過使用markdown解析器? (如果這是你使用它的唯一東西,但我認爲這會有點矯枉過正,但仍然認爲這值得推薦。) –

回答

1

您可以使用以下正則表達式等作爲

echo preg_replace("/\[(.*?)\]\((.*?)\)/","<a href='$2'>$1</a>",$x); 

Regex

-1
$x = str_replace("[homepage]", "<a href='www.example.com/homepage'>homepage</a>", $x);