>  기사  >  php教程  >  php网址转换为超链接方法

php网址转换为超链接方法

PHP中文网
PHP中文网원래의
2016-05-25 17:13:201365검색

PHP代码

//留言转换成网址
function strtr_str_to_url($str){
    $arr = array("www."=>"http://www.");
    $str = strtr($str,$arr);
    $arr = array("http://http://"=>"http://");
    $str = strtr($str,$arr);
    $str2 = explode("http://",$str);
    for($n = 1; isset($str2[$n]); $n ++){
        $str3 = explode(".",$str2[$n]);
        if(isset($str3[1])){
            $str4 = explode("www.",$str2[$n]);
            if((isset($str4[1]) && isset($str3[2])) || !isset($str4[1])){
                $length = strlen($str2[$n]);
                for($i = 0; $i <= $length; $i ++){
                    //从空格断开
                    if(($i - 1) == strlen(trim(mb_substr($str2[$n],0,$i,&#39;gb2312&#39;)))){
                        $ii = $i - 1;
                        $url1 = mb_substr($str2[$n],0,$ii,&#39;gb2312&#39;);
                        $url2 = mb_substr($str2[$n],$ii,$length,&#39;gb2312&#39;);
                        $url3 = "<a href=\"http://".$url1."\" target=\"_blank\">http://".$url1."</a>".$url2;
                        break;
                    }
                     
                    //从出现汉字处断开
                    if($i != strlen(mb_substr($str2[$n],0,$i,&#39;gb2312&#39;))){
                        $ii = $i - 1;
                        $url1 = mb_substr($str2[$n],0,$ii,&#39;gb2312&#39;);
                        $url2 = mb_substr($str2[$n],$ii,$length,&#39;gb2312&#39;);
                        $url3 = "<a href=\"http://".$url1."\" target=\"_blank\">http://".$url1."</a>".$url2;
                        break;
                    }
                    if($i == $length)$url3 = "<a href=\"http://".$str2[$n]."\" target=\"_blank\">http://".$str2[$n]."</a>";
                }
            }else $url3 = "http://".$str2[$n];
        }else $url3 = "http://".$str2[$n];
        $url .= $url3;
    }
    if(substr($str,0,7) == "http://") $url = "<a href=\"http://$str2[0]\" target=\"_blank\">".$str2[0]."</a>".$url;
    else $url = $str2[0].$url;
    return $url;
}

2. [代码][PHP]代码     

$str = "
http://127.0.0.1/test/str_to_url.php?id=1 2是http://127.0.0.1/test/str_to_url.php http://127.0.0.1/test/str_to_url.php是<br>
http://127.0.0.1/test/str_to_url.php啊<br>
http://127.0.0.1/test/str_to_url.php的<br>
http://www.baidu.com/home去<br>
http://www.baidu.com/home才<br>
www.baidu.com/homewww.baidu.com/home的<br>
www.baidu.com/home的<br>
www.baiducom/home才<br>
http://www.baiducom/home才
";
 
 
$str2 = strtr_msg_to_url($str);   
echo "$str2";


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.