什么是PHP正则表达式,可以将包含URL的文本转换为超链接? [英] What is the PHP regex to convert text containing a URL into a hyperlink?
问题描述
什么是用超链接替换字符串的正则表达式模式(在PHP中),其中URL之前的文本用作链接的锚文本?例如:
What's a regex pattern (in PHP) that replaces a string with hyperlinks, where the text preceding a URL is used as the anchor text for the link? For example:
text a http://example.com ending text
成为
<a href="http://example.com">text a</a> ending text
换句话说,URL之前的文本 成为链接的锚文本.
In other words, the text preceding the URL becomes the anchor text for the link.
我真正想要的是通过狙击以下功能的变体 http://www.snipe.net/2009/09/php- twitter-clickable-links/ 但随着上面的转折.
What I really want is a variation of the following function by snipe http://www.snipe.net/2009/09/php-twitter-clickable-links/ but with the twist above.
推荐答案
<?php
function twitterify($ret) {
//
// Replace all text that precedes a URL with an HTML anchor
// that hyperlinks the URL and shows the preceding text as
// the anchor text.
//
// e.g., "hello world www.test.com" becomes
// <a href="www.test.com" target="_blank">hello world</a>
//
$ret = preg_replace("#(.*?)(http://)?(www\.[^ \"\t\n\r<]+)#", "<a href=\"http://\\3\" target=\"_blank\">\\1</a>", $ret);
// if anchor text is empty, insert anchor's href
$ret = preg_replace("#(<a href=\"(\w+://)?([^\"]+)\"[^>]+>)(</a>)#", "\\1\\3\\4", $ret);
$ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
$ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
return $ret;
}
使用test()
...
function test($str) {
print "INPUT: \"" . $str . "\"\nOUTPUT: " . twitterify($str) . "\n\n";
}
// tests
test("www.foo.com");
test("www.foo.com fox");
test("www.test.com fox jumped over www.foo.com");
test("fox jumped over www.test.com the fence www.foo.com");
?>
...导致以下打印输出.
...results in the following print-outs.
INPUT: "www.foo.com"
OUTPUT: <a href="http://www.foo.com" target="_blank">www.foo.com</a>
INPUT: "www.foo.com fox"
OUTPUT: <a href="http://www.foo.com" target="_blank">www.foo.com</a> fox
INPUT: "www.test.com fox jumped over www.foo.com"
OUTPUT: <a href="http://www.test.com" target="_blank">www.test.com</a><a href="http://www.foo.com" target="_blank"> fox jumped over </a>
INPUT: "fox jumped over www.test.com the fence www.foo.com"
OUTPUT: <a href="http://www.test.com" target="_blank">fox jumped over </a><a href="http://www.foo.com" target="_blank"> the fence </a>
在 ideone 上进行了测试.
编辑:已更新代码以符合新要求
EDIT: Updated code to match new requirements
这篇关于什么是PHP正则表达式,可以将包含URL的文本转换为超链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!