我需要一个表单来自动链接用户在文本字段中输入的链接。我在堆栈上找到了一个完美运行的示例,除了一件事。如果用户输入的链接不包含http://
orhttps://
而是仅使用www.
该链接启动链接将无法正常工作。
即用户输入将是
check out our twitter!
www.twitter.com/#!/profile
and our facebook!
https://www.facebook.com/profile
输出将是
check out our twitter!
<a href="www.twitter.com/#!/profile">www.twitter.com/#!/profile</a>
and our facebook!
<a href="https://www.facebook.com/profile">http://www.facebook.com/profile</a>
所以 facebook 链接可以完美运行,但 twitter 不会,因为它链接到用户所在的当前位置加上新链接,即如果他们当前在链接上www.example.com
,则链接将变为www.example.com/www.twitter.com/#!/profile
对于我的生活,我无法弄清楚如何通过简单地将 http:// 添加到链接的开头来解决这个问题,这是功能:
function auto_link_text($text) {
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
return preg_replace_callback($pattern, 'auto_link_text_callback', $text);
}
function auto_link_text_callback($matches) {
$max_url_length = 50;
$max_depth_if_over_length = 2;
$ellipsis = '…';
$url_full = $matches[0];
$url_short = '';
if (strlen($url_full) > $max_url_length) {
$parts = parse_url($url_full);
$url_short = $parts['scheme'] . '://' . preg_replace('/^www\./', '', $parts['host']) . '/';
$path_components = explode('/', trim($parts['path'], '/'));
foreach ($path_components as $dir) {
$url_string_components[] = $dir . '/';
}
if (!empty($parts['query'])) {
$url_string_components[] = '?' . $parts['query'];
}
if (!empty($parts['fragment'])) {
$url_string_components[] = '#' . $parts['fragment'];
}
for ($k = 0; $k < count($url_string_components); $k++) {
$curr_component = $url_string_components[$k];
if ($k >= $max_depth_if_over_length || strlen($url_short) + strlen($curr_component) > $max_url_length) {
if ($k == 0 && strlen($url_short) < $max_url_length) {
// Always show a portion of first directory
$url_short .= substr($curr_component, 0, $max_url_length - strlen($url_short));
}
$url_short .= $ellipsis;
break;
}
$url_short .= $curr_component;
}
} else {
$url_short = $url_full;
}
return "<a rel=\"nofollow\" href=\"$url_full\">$url_short</a>";
}