PHP将字符串中的URL转换为可点击的链接

PHP 7.0已经移除了eregi_replace方法,导致之前url或者email字符串使用eregi_replace转换的方法失效:

之前的老方法(php7.0已废弃)
function str2url($text)
{
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)','\1', $text);
    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)','\1\2', $text);
    $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})','\1', $text);
    return $text;
}
现调整为(php7.0可用)
function str2url($str= '')
{
    if ($str== '' or !preg_match('/(http|ftp|www\.|@)/i', $str)) {
        return $str;
    }
    $lines = explode("\n", $str);
    $text  = '';
    while (list($k, $v) = each($lines)) {
        // replace links:
        $v = preg_replace("/([\t]|^)www\./i", "\\1http://www.", $v);
        $v = preg_replace("/([\t]|^)ftp\./i", "\\1ftp://ftp.", $v);
        $v = preg_replace("/(http:\/\/[^)!]+)/i", "\\1", $v);
        $v = preg_replace("/(https:\/\/[^)!]+)/i", "\\1", $v);
        $v = preg_replace("/(ftp:\/\/[^)!]+)/i", "\\1", $v);
        $v = preg_replace("/([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})/i", "\\1", $v);
        $text .= $v . "\n";
     }
     return $text;
}

你可能感兴趣的:(PHP将字符串中的URL转换为可点击的链接)