1

我正在尝试编写一个函数来在 URL 之前和之后的字符串中插入一些东西(如果有的话)。例如,一个字符串可能是这样的

"This is a string and some links, http://www.abc.com/xyz.html&p=123 and the other link is http://www.xyz.com/abc.html&x=2, that's all."

我想将其更改为(在 URL 之前和之后添加一些 html 标签)

"This is a string and some links, <a href="...">http://www.abc.com/xyz.html&p=123</a> and the other link is <a href="...">http://www.xyz.com/abc.html&x=2</a >, that's all."

实际上,我之前编写了一个 Lua 函数,通过使用 string.find() 来查找 http 并递归地解析字符串来做类似的事情。

我对 PHP 比较陌生,想知道 PHP 是否有任何功能或技术可以更轻松地执行此任务?

4

2 回答 2

2

这里的问题是结束字符。例如,“我去了http://example.com/。我找到了...”或“您访问过http://example.com/吗?”

现在,如果你可以假设 URL 的末尾总是有一个空格并且它总是以 http:// 开头,那么试试这个:

$url = preg_replace('/(https?:\/\/[^ ]+) /', '<a href="$1">$1</a>', $url);
于 2013-11-13T04:39:17.757 回答
1

好吧,这是一个开始。但请记住,您可能会遇到一些问题。我会在代码之后说。

$text = "This is a string and some links, http://www.abc.com/xyz.html&p=123 and the other link is http://www.xyz.com/abc.html&x=2";
preg_replace("/(http:)([^ ,]*)/", "<a href=\"$1$2\">$1$2</a>", $text);

您可能遇到的问题是,当您在 url 之后有一些字符串时,例如您的示例文本:This is a string and some links, http://www.abc.com/xyz.html&p=123 and the other link is http://www.xyz.com/abc.html&x=2, that's all.url 后面有一个逗号,因此您必须将其放入您的正则表达式中,就像 id 在我的回答中所做的那样并更改咬你的文字。

在我的表达中,我正在考虑 URL 以非空格字符(或者,在您的特定情况下,逗号)的任何内容开头http和结尾。

于 2013-11-13T04:38:17.710 回答