如何模拟堆栈溢出自动链接行为 [英] How to mimic Stack Overflow Auto-Link Behavior
本文介绍了如何模拟堆栈溢出自动链接行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用PHP模仿Stack Overflow(它的BTW非常酷)的自动链接行为?
With PHP how can I mimic the auto-link behavior of Stack Overflow (which BTW is awesomely cool)?
例如,以下URL:
http://www.stackoverflow.com/questions/1925455 /how-to-mimic-stackoverflow-auto-link-behavior
已转换为:
<a title="how to mimic stackoverflow auto link behavior" rel="nofollow" href="http://www.stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior">stackoverflow.com/questions/1925455/…</a>
在这种情况下,我不太在意title
属性.
I don't really care for the title
attribute in this case.
这:
http://pt.php.net/manual /en/function.base-convert.php#52450
已转换为:
<a rel="nofollow" href="http://pt.php.net/manual/en/function.base-convert.php#52450">pt.php.net/manual/en/…</a>
如何在PHP中进行类似的功能?
How can I make a similar function in PHP?
PS:请查看我对此问题的评论,以获取更多示例和行为.
推荐答案
尝试一下.网址匹配的正则表达式模式来自发怒的火球.
Try this out. The URL-matching regex pattern is from Daring Fireball.
/**
* Replace links in text with html links
*
* @param string $text
* @return string
*/
function auto_link_text($text)
{
// a more readably-formatted version of the pattern is on http://daringfireball.net/2010/07/improved_regex_for_matching_urls
$pattern = '(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»""‘’]))';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
$last = -(strlen(strrchr($text, "/"))) + 1;
if ($last < 0) {
$text = substr($text, 0, $last) . "…";
}
return sprintf(\'<a rel="nofollow" href="%s">%s</a>\', $url, $text);
');
return preg_replace_callback($pattern, $callback, $text);
}
输入文字:
This is my text. I wonder if you know about asking questions on StackOverflow:
Check This out http://www.stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior
Also, base_convert php function?
http://pt.php.net/manual/en/function.base-convert.php#52450
http://pt.php.net/manual/en/function.base-convert.php?wtf=hehe#52450
输出文本:
This is my text. I wonder if you know about asking questions on StackOverflow:
Check This out <a rel="nofollow" href="http://www.stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior">stackoverflow.com/questions/1925455/…</a>
Also, base_convert php function?
<a rel="nofollow" href="http://pt.php.net/manual/en/function.base-convert.php#52450">pt.php.net/manual/en/…</a>
<a rel="nofollow" href="http://pt.php.net/manual/en/function.base-convert.php?wtf=hehe#52450">pt.php.net/manual/en/…</a>
这篇关于如何模拟堆栈溢出自动链接行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文