模仿 Stack Overflow 的自动链接功能
要增强 Web 内容,请考虑模拟 Stack Overflow 的自动链接功能。此函数可以将纯 URL 转换为视觉上吸引人的超链接。
在 PHP 中实现
这是一个受 Stack Overflow 行为启发的 PHP 函数:
<code class="php">function auto_link_text($text) { // URL matching regex pattern from Daring Fireball $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) . "&hellip;"; } return sprintf(\'<a rel="nofollow" href="%s">%s</a>\', $url, $text); '); return preg_replace_callback($pattern, $callback, $text); }</code>
用法示例
考虑以下输入文本:
<code class="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</code>
使用 auto_link_text 函数,此文本将被转换:
<code class="html">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></code>
自定义
您可以通过修改回调函数来定制链接行为。例如,您可以:
通过调整实现,您可以创建满足您特定需求的自定义自动链接解决方案。
以上是如何在 PHP 中模仿 Stack Overflow 的自动链接功能?的详细内容。更多信息请关注PHP中文网其他相关文章!