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

2018-05-31  本文已影响0人  Firstmeet初见

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@:%_+.~#?&//=]+)','<a class="str2url external" target="_blank" href="\1">\1</a>', $text);
    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)','\1<a class="str2url external" target="_blank" href="http://\2">\2</a>', $text);
    $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})','<a class="str2url external" href="mailto:\1">\1</a>', $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", "<a class=\"str2url external\" target=\"_blank\" href=\"\\1\">\\1</a>", $v);
        $v = preg_replace("/(https:\/\/[^)!]+)/i", "<a class=\"str2url external\" target=\"_blank\" href=\"\\1\">\\1</a>", $v);
        $v = preg_replace("/(ftp:\/\/[^)!]+)/i", "<a class=\"str2url external\" target=\"_blank\" href=\"\\1\">\\1</a>", $v);
        $v = preg_replace("/([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})/i", "<a class=\"str2url external\" href=\"mailto:\\1\">\\1</a>", $v);
        $text .= $v . "\n";
     }
     return $text;
}
上一篇下一篇

猜你喜欢

热点阅读