使用 preg_replace() 将 url 转换为字符串中的链接

Converting urls to links in a string using preg_replace()

我正在尝试将 url 转换为字符串中的 links

我有以下字符串:

$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.

我想将 [ 和 ] 中的所有内容转换为 link 标题,并将 ( 和 ) 中的所有内容转换为 href 属性的值:

欢迎访问我的 homepage ,Please check our 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=''></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.

我的代码有问题吗?

请帮忙!

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

您可以使用以下正则表达式,如

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

Regex