欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

各种有用的函数 自己亲自做的写的

<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/4/25
 * Time: 15:00
 */
function my_substr($str,$len,$suf=''){
    $strlen = strlen($str);
 
    if($strlen<=$len){
        return $str;
    }
    return substr($str,0,$len).$suf;
}
//二维数组变一维,第一个参是二维数组,第二个是数组里的字段名
function twoArrayToOne($rows,$title='title')
{
    if(empty($rows)){
        return array();
    }
    $newOneArr = array();
    foreach($rows as $row){
        $newOneArr[]= $row[$title];
    }
    return $newOneArr;
}
 
 
//把二维数组合成一维数组
function arrayTwoToOne($oldArr = "", $f1 = 'id', $f2 = 'title'){
    foreach($oldArr as $key=>$value)
    {
        $newArr[$value[$f1]]=$value[$f2];
    }
    return $newArr;
}
 
//称除回车tab键
function removeEnterTab($str)
{
    return preg_replace('/[\n\r\t]/', '',$str);
}
//去掉首尾的中英文空格 (中文英文空格)
function removeCnEnSpace($str)
{
    return mb_ereg_replace('(^( | )+|( | )+$)', '', $str);
}
 
function safe_func_array($arr)
{
    foreach ( $arr as $key => $value ) {
        $arr[$key] = safe_func($value);
    }
    return $arr;
}
 
 
function safe_func($str){
    //$vowels = array("\\","$","%","^","&","*",'<','>');
    $vowels = array("\\","$","^","*");
    $str = str_replace($vowels, "", $str);
    empty($str) && $str='';
    return $str;
}
function getFullFilename($url, $domain){
// if(stripos($url,'?')>0){
// $url = substr($url,0,stripos($url,'?'));
// }
    $requestUrl = substr($url,strlen($domain)+1);
// $url = preg_replace('/\=+?/misU',"X",$url);
    $requestUrl = preg_replace('/\={2,}/misU',"=",$requestUrl);
    $requestUrl = str_replace(array('_','-'),'',$requestUrl);
    $requestUrl = preg_replace('/#\w*?/misU',"",$requestUrl);
    $requestUrl = preg_replace('/&(\w*?)=/misU',"",$requestUrl);
    $requestUrl = str_replace(array('?','='), "/", $requestUrl);
    $requestUrl = preg_replace('/\/{2,}/misU',"/",$requestUrl);
    $requestUrlArr = explode('/',$requestUrl);
    $lastPath = $requestUrlArr[count($requestUrlArr)-1];
    $lastPath = preg_replace('/\..*?/misU',".html",$lastPath);
    //$lastPath = preg_replace('#\..*?#misU',".html",$lastPath);
    if(empty(strrchr($lastPath,'.'))){
        $lastPath = 'index.html';
    }
    foreach($requestUrlArr as $key=>$value){
        if(strrchr($value,'.')){
            unset($requestUrlArr[$key]);
        }
    }
    $pathname = '';
    foreach($requestUrlArr as $key=>$value){
        if(empty($value)){
            continue;
        }
        $pathname .= $value.'/';
    }
 
    $filename  = $pathname.$lastPath;
// var_dump($filename);exit;
    return $filename;
 
}
//根据url得到域名 根据路径 得到域名
function getDomainByUrl($url)
{
    $domainPos = newstripos($url,'/',3);
    if(empty($domainPos)){
        $domain = $url;
    }else {
        $domain = substr($url,0,$domainPos);
    }
 
    return $domain;
}
//根据url得到url的路径 比如 http://www.aaa.com/aaa/bb.html 就得到 http://www.aaa.com/aaa/
function getDirUrlByUrl($url)
{
    if(stripos($url,'?')>0){
        $url = substr($url,0,stripos($url,'?'));
    }
    $lastSuff = strtolower(strrchr($url,'.'));
    //假如后缀名不是这些的话
    if( $lastSuff!='.asp' &&  $lastSuff!='.php' &&  $lastSuff!='.htm' &&  $lastSuff!='.html'
        &&  $lastSuff!='.jsp' &&  $lastSuff!='.aspx' &&  $lastSuff!='.py' &&  $lastSuff!='.shtml'
        &&  $lastSuff!='.do' &&  $lastSuff!='.shtm'){
        $dirUrl = $url;
    }else{
        $lastPos = strripos($url,'/');
        $dirUrl = substr($url,0,$lastPos);
    }
    if (strrchr($dirUrl,'/')=='/'){
        $dirUrl = substr($dirUrl,0,strlen($dirUrl)-1);
    }
    return $dirUrl;
}
//查找字符串 第几次出现的位置
//写一个新的stripos, $count参数表示第count次出现的问题
function newstripos($str, $find, $count, $offset=0)
{
    $pos = stripos($str, $find, $offset);
    $count--;
    if ($count > 0 && $pos !== FALSE)
    {
        $pos = newstripos($str, $find ,$count, $pos+1);
    }
    return $pos;
}
 
 
function detectEncode($str)
{
    if(isUtf8($str)){
        return "UTF-8";
    }
    else{
        return   mb_detect_encoding($str, array('ASCII','GB2312','GBK','BIG5'));
    }
}
 
 
function isUtf8($str)
{
    $score =   utf8_probability($str);
    if($score>90)return true;
    return 0;
}
 
function utf8_probability($rawtextstr) {
    $score = 0;
    $i = 0;
    $rawtextlen = 0;
    $goodbytes = 0;
    $asciibytes = 0;
    $rawtextarray = preg_split("//",$rawtextstr,-1, PREG_SPLIT_NO_EMPTY); //转换成char数组,如果是php5,则可使用str_split
    $rawtext = array();
//var_dump($rawtextarray);die;
    for($i=0;$i<count($rawtextarray);$i++)
        $rawtext[] = ord($rawtextarray[$i]); //ord(char)
// Maybe also use UTF8 Byte Order Mark(BOM): EF BB BF
//BOM,某些utf8文件流的首3个字节,可以表示这个文件的编码方式
// Check to see if characters fit into acceptable ranges
//print_r($rawtext);
    $rawtextlen = strlen($rawtextstr);
    for ($i = 0; $i < $rawtextlen; $i++) {
        if ($rawtext[$i] < 0x80) { // One byte
            $asciibytes++; // Ignore ASCII, can throw off count
        } else if (0xC0 <= $rawtext[$i] && $rawtext[$i] <= 0xDF && // Two bytes
            $i+1 < $rawtextlen && 0x80 <= $rawtext[$i+1] && $rawtext[$i+1] <= 0xBF) {
            $goodbytes += 2; $i++;
        } else if (0xE0 <= $rawtext[$i] && $rawtext[$i] <= 0xEF && // Three bytes
            $i+2 < $rawtextlen && 0x80 <= $rawtext[$i+1] && $rawtext[$i+1] <= 0xBF &&
            0x80 <= $rawtext[$i+2] && $rawtext[$i+2] <= 0xBF) {
            $goodbytes += 3; $i+=2;
        }
//if you want check just a few ,you may stop here with a score make.
//or you will be delayed when you meet lots of big files.
    }
//ascii is sub of utf8
    if ($asciibytes == $rawtextlen) { return 0; }
    $score = (int)(100 * ($goodbytes/($rawtextlen-$asciibytes)));
// If not above 98, reduce to zero to prevent coincidental matches
    if ($score > 98) {
        return $score;
    } else if ($score > 95 && $goodbytes > 30) {
// Allows for some (few) bad formed sequences
        return $score;
    } else {
        return 0;
    }
}
//它的目的是采用主域名 作为第一个目录
function getFirstDir($str)
{
    $str = substr($str,7);
    $arr = explode('.',$str,3);
    return $arr[count($arr)-2];
}
function startWith($str, $needle) {
 
    return strpos($str, $needle) === 0;
 
}
function endWith($haystack, $needle) {
 
    $length = strlen($needle);
    if($length == 0)
    {
        return true;
    }
    return (substr($haystack, -$length) === $needle);
}
function changeCss($matches)
{
    global $domain;
    global $dirUrl;
    if (startWith($matches[2],'/')){
        return '<link '.$matches[1].' href="'.$domain.$matches[2].'" '.$matches[3].'/>';
    }
    else if(startWith($matches[2],'http://')){
        return '<link '.$matches[1].' href="'.$matches[2].'" '.$matches[3].'/>';
    }
    else {
        return '<link '.$matches[1].' href="'.$dirUrl.'/'.$matches[2].'" '.$matches[3].'/>';
    }
}
function changeJs($matches)
{
    global $domain;
    global $dirUrl;
 
    if (startWith($matches[2],'/')){
        return '<script '.$matches[1].' src="'.$domain.$matches[2].'"  '.$matches[3].'  >'.$matches[4].'</script> ';
    }
    else if(startWith($matches[2],'http://')){
        return '<script '.$matches[1].' src="'.$matches[2].'"  '.$matches[3].'  >'.$matches[4].'</script> ';
    }
    else {
        return '<script '.$matches[1].' src="'.$dirUrl.'/'.$matches[2].'"  '.$matches[3].'  >'.$matches[4].'</script> ';
    }
}
 
function changeImg($matches)
{
    global $domain;
    global $dirUrl;
 
    if (startWith($matches[2],'/')){
        return '<img '.$matches[1].'src="'.$domain.$matches[2].'" '.$matches[3].' /> ';
    }
    else if(startWith($matches[2],'http://')){
        return '<img '.$matches[1].'src="'.$matches[2].'" '.$matches[3].' /> ';
    }
    else {
        return '<img '.$matches[1].'src="'.$dirUrl.'/'.$matches[2].'" '.$matches[3].' /> ';
    }
}
function changeDataOriginalImg($matches)
{
    global $domain;
    global $dirUrl;
 
    if (startWith($matches[2],'/')){
        return '<img '.$matches[1].'data-original="'.$domain.$matches[2].'" '.$matches[3].' /> ';
    }
    else if(startWith($matches[2],'http://')){
        return '<img '.$matches[1].'data-original="'.$matches[2].'" '.$matches[3].' /> ';
    }
    else {
        return '<img '.$matches[1].'data-original="'.$dirUrl.'/'.$matches[2].'" '.$matches[3].' /> ';
    }
 
}
function changeBackImg($matches)
{
    global $domain;
    global $dirUrl;
    if (startWith($matches[3],'/')){
        return 'background'.$matches[1].'url('.$matches[2].$domain.$matches[3].$matches[4].')';
    }
    else if(startWith($matches[3],'http://')){
        return 'background'.$matches[1].'url('.$matches[2].$matches[3].$matches[4].')';
    }
    else {
        return 'background'.$matches[1].'url('.$matches[2].$dirUrl.'/'.$matches[3].$matches[4].')';
    }
 
}
function isImgUrl($imgUrl){
    return endWith($imgUrl,'.jpg') || endWith($imgUrl,'.jpeg') || endWith($imgUrl,'.gif') || endWith($imgUrl,'.png') || endWith($imgUrl,'.bmp');
}
function saveImgContent($imgUrl){
    global $domain;
    global $dirUrl;
    if(isImgUrl($imgUrl)){
        $imgContent = @file_get_contents($imgUrl);
        if(!empty($imgContent)){
            saveContent(public_path().'/html'.substr($imgUrl,strlen($domain)),$imgContent);
        }
    }
}
function saveImg($matches){
 
    global $domain;
    global $dirUrl;
    if (startWith($matches[2],'/')){
        $imgUrl = $domain.$matches[2];
    }
    else if(startWith($matches[2],'http://')){
        $imgUrl = $matches[2];
    }
    else {
        $imgUrl = $dirUrl.'/'.$matches[2];
    }
    saveImgContent($imgUrl);
    return '';
}
function saveBackImg($matches){
    global $domain;
    global $dirUrl;
    if (startWith($matches[3],'/')){
        $imgUrl = $domain.$matches[3];
    }
    else if(startWith($matches[3],'http://')){
        $imgUrl = $matches[3];
    }
    else {
        $imgUrl = $dirUrl.'/'.$matches[3];
    }
    saveImgContent($imgUrl);
    return '';
}
function ChuliJsImg($urls)
{
 
    global $domain;
    global $dirUrl;
    foreach($urls as $key=>$value){
 
 
        $jsContent = @file_get_contents($value);
        if(!stristr($jsContent,'<img') && !stristr($jsContent,'background')){
            continue;
        }
        preg_replace_callback('/<img(.*)src=["\']([^>]+)["\'](.*)\/?>/misU','saveImg',$jsContent);
        preg_replace_callback('/background(.*)url\((["\']?)([^>]+)(["\']?)\)/misU','saveBackImg',$jsContent);
    }
}
function saveContent($fullname,$content){
 
    if(!is_dir(dirname($fullname))) {
 
        mkdir(dirname($fullname), 0755, true);//这里true表示可以创建多级目录
    }
 
    //if(!file_exists($fullname)){
    $fp = @fopen($fullname,"w") or die("写文件失败");
    fwrite($fp,$content);
    fclose($fp);
    //}
 
}
function nullSetSring($str)
{
    if(empty($str)){
        return '';
    }
}
function nullSetArr($arr='')
{
    if(!is_array($arr)){
        if(empty($arr)){
            return '';
        }else{
            return $arr;
        }
    }
    foreach($arr as $key=>$value){
        $value =  nullSetArr($value);
        $arr[$key] = $value;
    }
    return $arr;
}
 
function existFullnameChangeName($fullname)
{
    $i=0;
    $pre_name = substr($fullname,0,strripos($fullname,'.'));
    $suff_name = strrchr($fullname,'.');
    while(file_exists($fullname)){
        $i++;
        $fullname = $pre_name.$i.$suff_name;
    }
    return $fullname;
}
 
function preSaveOrigUrl($orig_url, $request)
{
    global $domain;
    global $dirUrl;
    $domain = getDomainByUrl($orig_url);
    $dirUrl = getDirUrlByUrl($orig_url);
    $content = @file_get_contents($orig_url);
    if(empty($content)){
        return '-1';
    }
 
 
    $firstPath = getFirstDir($domain);
    $fullname = getFullFilename($orig_url, $domain);
 
    $charset = detectEncode($content);
    if($charset!='UTF-8'){
        $content = iconv($charset,'UTF-8',$content);
    }
 
    $content = preg_replace_callback('/<link(.*)href=["\']([^>]+)["\'](.*)\/?>/misU','changeCss',$content);
    $content = preg_replace_callback('/<script([^>]*)src=["\']([^>]+)["\'](.*)>(.*)<\/script>/misU','changeJs',$content);
    $content = preg_replace_callback('/<img(.*)src=["\']([^>]+)["\'](.*)\/?>/misU','changeImg',$content);
    //处理延迟加载
    $content = preg_replace_callback('/<img(.*)data-original=["\']([^>]+)["\'](.*)\/?>/misU','changeDataOriginalImg',$content);
    $content = preg_replace_callback('/background(.*)url\((["\']?)([^>]+)(["\']?)\)/misU','changeBackImg',$content);
 
    //js 里面的图像
    preg_match_all('/<script([^>]*)src=["\']([^>]+)["\'](.*)>(.*)<\/script>/misU',$content,$out,PREG_PATTERN_ORDER);
    $jsUrls = $out[2];
 
    ChuliJsImg($jsUrls);
    //$fullname_script_name  = '/html/'.$firstPath.'/'.$fullname;
    $fullname = public_path().'/html/'.$firstPath.'/'.$fullname;
    //如果已经存在的话
    $fullname = existFullnameChangeName($fullname);
 
    $local_url = 'http://'.$request->server("HTTP_HOST").substr($fullname,strlen(public_path()));
 
    //抓取QQ网站好像有点问题
    //$content = str_replace("'qq.com'","'".$_SERVER['HTTP_HOST']."'",$content);
    //$content = str_replace('"qq.com"','"'.$_SERVER['HTTP_HOST'].'"',$content);
 
    return compact('fullname', 'content', 'local_url');
 
 
 
}
?>




<?php
 
 
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/4/25
 * Time: 15:00
 */
function my_substr($str,$len,$suf=''){
    $strlen = strlen($str);
 
    if($strlen<=$len){
        return $str;
    }
    return substr($str,0,$len).$suf;
}
//二维数组变一维,第一个参是二维数组,第二个是数组里的字段名
function twoArrayToOne($rows,$title='title')
{
    if(empty($rows)){
        return array();
    }
    $newOneArr = array();
    foreach($rows as $row){
        $newOneArr[]= $row[$title];
    }
    return $newOneArr;
}
 
 
//把二维数组合成一维数组
function arrayTwoToOne($oldArr = "", $f1 = 'id', $f2 = 'title'){
    foreach($oldArr as $key=>$value)
    {
        $newArr[$value[$f1]]=$value[$f2];
    }
    return $newArr;
}
 
//称除回车tab键
function removeEnterTab($str)
{
    return preg_replace('/[\n\r\t]/', '',$str);
}
//去掉首尾的中英文空格 (中文英文空格)
function removeCnEnSpace($str)
{
    return mb_ereg_replace('(^( | )+|( | )+$)', '', $str);
}
 
function safe_func_array($arr)
{
    foreach ( $arr as $key => $value ) {
        $arr[$key] = safe_func($value);
    }
    return $arr;
}
 
 
function safe_func($str){
    //$vowels = array("\\","$","%","^","&","*",'<','>');
    $vowels = array("\\","$","^","*");
    $str = str_replace($vowels, "", $str);
    empty($str) && $str='';
    return $str;
}
function getFullFilename($url, $domain){
// if(stripos($url,'?')>0){
// $url = substr($url,0,stripos($url,'?'));
// }
    $requestUrl = substr($url,strlen($domain)+1);
// $url = preg_replace('/\=+?/misU',"X",$url);
    $requestUrl = preg_replace('/\={2,}/misU',"=",$requestUrl);
    $requestUrl = str_replace(array('_','-'),'',$requestUrl);
    $requestUrl = preg_replace('/#\w*?/misU',"",$requestUrl);
    $requestUrl = preg_replace('/&(\w*?)=/misU',"",$requestUrl);
    $requestUrl = str_replace(array('?','='), "/", $requestUrl);
    $requestUrl = preg_replace('/\/{2,}/misU',"/",$requestUrl);
    $requestUrlArr = explode('/',$requestUrl);
    $lastPath = $requestUrlArr[count($requestUrlArr)-1];
    $lastPath = preg_replace('/\..*?/misU',".html",$lastPath);
    //$lastPath = preg_replace('#\..*?#misU',".html",$lastPath);
    if(empty(strrchr($lastPath,'.'))){
        $lastPath = 'index.html';
    }
    foreach($requestUrlArr as $key=>$value){
        if(strrchr($value,'.')){
            unset($requestUrlArr[$key]);
        }
    }
    $pathname = '';
    foreach($requestUrlArr as $key=>$value){
        if(empty($value)){
            continue;
        }
        $pathname .= $value.'/';
    }
 
    $filename  = $pathname.$lastPath;
// var_dump($filename);exit;
    return $filename;
 
}
 
function getDomainByUrl($url)
{
    $domainPos = newstripos($url,'/',3);
    if(empty($domainPos)){
        $domain = $url;
    }else {
        $domain = substr($url,0,$domainPos);
    }
 
    return $domain;
}
 
function getDirUrlByUrl($url)
{
    if(stripos($url,'?')>0){
        $url = substr($url,0,stripos($url,'?'));
    }
    $lastSuff = strtolower(strrchr($url,'.'));
    //假如后缀名不是这些的话
    if( $lastSuff!='.asp' &&  $lastSuff!='.php' &&  $lastSuff!='.htm' &&  $lastSuff!='.html'
        &&  $lastSuff!='.jsp' &&  $lastSuff!='.aspx' &&  $lastSuff!='.py' &&  $lastSuff!='.shtml'
        &&  $lastSuff!='.do' &&  $lastSuff!='.shtm'){
        $dirUrl = $url;
    }else{
        $lastPos = strripos($url,'/');
        $dirUrl = substr($url,0,$lastPos);
    }
    if (strrchr($dirUrl,'/')=='/'){
        $dirUrl = substr($dirUrl,0,strlen($dirUrl)-1);
    }
    return $dirUrl;
}
//查找字符串 第几次出现的位置
//写一个新的stripos, $count参数表示第count次出现的问题
function newstripos($str, $find, $count, $offset=0)
{
    $pos = stripos($str, $find, $offset);
    $count--;
    if ($count > 0 && $pos !== FALSE)
    {
        $pos = newstripos($str, $find ,$count, $pos+1);
    }
    return $pos;
}
 
 
function detectEncode($str)
{
    if(isUtf8($str)){
        return "UTF-8";
    }
    else{
        return   mb_detect_encoding($str, array('ASCII','GB2312','GBK','BIG5'));
    }
}
 
 
function isUtf8($str)
{
    $score =   utf8_probability($str);
    if($score>90)return true;
    return 0;
}
 
function utf8_probability($rawtextstr) {
    $score = 0;
    $i = 0;
    $rawtextlen = 0;
    $goodbytes = 0;
    $asciibytes = 0;
    $rawtextarray = preg_split("//",$rawtextstr,-1, PREG_SPLIT_NO_EMPTY); //转换成char数组,如果是php5,则可使用str_split
    $rawtext = array();
//var_dump($rawtextarray);die;
    for($i=0;$i<count($rawtextarray);$i++)
        $rawtext[] = ord($rawtextarray[$i]); //ord(char)
// Maybe also use UTF8 Byte Order Mark(BOM): EF BB BF
//BOM,某些utf8文件流的首3个字节,可以表示这个文件的编码方式
// Check to see if characters fit into acceptable ranges
//print_r($rawtext);
    $rawtextlen = strlen($rawtextstr);
    for ($i = 0; $i < $rawtextlen; $i++) {
        if ($rawtext[$i] < 0x80) { // One byte
            $asciibytes++; // Ignore ASCII, can throw off count
        } else if (0xC0 <= $rawtext[$i] && $rawtext[$i] <= 0xDF && // Two bytes
            $i+1 < $rawtextlen && 0x80 <= $rawtext[$i+1] && $rawtext[$i+1] <= 0xBF) {
            $goodbytes += 2; $i++;
        } else if (0xE0 <= $rawtext[$i] && $rawtext[$i] <= 0xEF && // Three bytes
            $i+2 < $rawtextlen && 0x80 <= $rawtext[$i+1] && $rawtext[$i+1] <= 0xBF &&
            0x80 <= $rawtext[$i+2] && $rawtext[$i+2] <= 0xBF) {
            $goodbytes += 3; $i+=2;
        }
//if you want check just a few ,you may stop here with a score make.
//or you will be delayed when you meet lots of big files.
    }
//ascii is sub of utf8
    if ($asciibytes == $rawtextlen) { return 0; }
    $score = (int)(100 * ($goodbytes/($rawtextlen-$asciibytes)));
// If not above 98, reduce to zero to prevent coincidental matches
    if ($score > 98) {
        return $score;
    } else if ($score > 95 && $goodbytes > 30) {
// Allows for some (few) bad formed sequences
        return $score;
    } else {
        return 0;
    }
}
//它的目的是采用主域名 作为第一个目录
function getFirstDir($str)
{
    $str = substr($str,7);
    $arr = explode('.',$str,3);
    return $arr[count($arr)-2];
}
function startWith($str, $needle) {
 
    return strpos($str, $needle) === 0;
 
}
function endWith($haystack, $needle) {
 
    $length = strlen($needle);
    if($length == 0)
    {
        return true;
    }
    return (substr($haystack, -$length) === $needle);
}
function changeCss($matches)
{
    global $domain;
    global $dirUrl;
    if (startWith($matches[2],'/')){
        return '<link '.$matches[1].' href="'.$domain.$matches[2].'" '.$matches[3].'/>';
    }
    else if(startWith($matches[2],'http://')){
        return '<link '.$matches[1].' href="'.$matches[2].'" '.$matches[3].'/>';
    }
    else {
        return '<link '.$matches[1].' href="'.$dirUrl.'/'.$matches[2].'" '.$matches[3].'/>';
    }
}
function changeJs($matches)
{
    global $domain;
    global $dirUrl;
 
    if (startWith($matches[2],'/')){
        return '<script '.$matches[1].' src="'.$domain.$matches[2].'"  '.$matches[3].'  >'.$matches[4].'</script> ';
    }
    else if(startWith($matches[2],'http://')){
        return '<script '.$matches[1].' src="'.$matches[2].'"  '.$matches[3].'  >'.$matches[4].'</script> ';
    }
    else {
        return '<script '.$matches[1].' src="'.$dirUrl.'/'.$matches[2].'"  '.$matches[3].'  >'.$matches[4].'</script> ';
    }
}
 
function changeImg($matches)
{
    global $domain;
    global $dirUrl;
 
    if (startWith($matches[2],'/')){
        return '<img '.$matches[1].'src="'.$domain.$matches[2].'" '.$matches[3].' /> ';
    }
    else if(startWith($matches[2],'http://')){
        return '<img '.$matches[1].'src="'.$matches[2].'" '.$matches[3].' /> ';
    }
    else {
        return '<img '.$matches[1].'src="'.$dirUrl.'/'.$matches[2].'" '.$matches[3].' /> ';
    }
}
function changeDataOriginalImg($matches)
{
    global $domain;
    global $dirUrl;
 
    if (startWith($matches[2],'/')){
        $str =  '<img '.$matches[1].'data-original="'.$domain.$matches[2].'" '.$matches[3].' ';
        $str = str_ireplace('<img','<img src="'.$domain.$matches[2].'"',$str);
        //$str = str_replace('src=','oldsrc=',$str);
        //$str = $str. ' src="'.$domain.$matches[2].'"'.' />';
        return $str;
 
    }
    else if(startWith($matches[2],'http://')){
        $str =  '<img '.$matches[1].'data-original="'.$matches[2].'" '.$matches[3].' ';
        $str = str_ireplace('<img','<img src="'.$matches[2].'"',$str);
//        $str = str_ireplace('src=','oldsrc=',$str);
//        $str = $str. ' src="'.$matches[2].'"'.' />';
        return $str;
    }
    else {
        $str =  '<img '.$matches[1].'data-original="'.$dirUrl.'/'.$matches[2].'" '.$matches[3].' ';
        $str = str_ireplace('<img','<img src="'.$dirUrl.$matches[2].'"',$str);
//        $str = str_ireplace('src=','oldsrc=',$str);
//        $str = $str. ' src="'.$dirUrl.'/'.$matches[2].'"'.' />';
        return $str;
    }
 
}
function changeBackImg($matches)
{
    global $domain;
    global $dirUrl;
    if (startWith($matches[3],'/')){
        return 'background'.$matches[1].'url('.$matches[2].$domain.$matches[3].$matches[4].')';
    }
    else if(startWith($matches[3],'http://')){
        return 'background'.$matches[1].'url('.$matches[2].$matches[3].$matches[4].')';
    }
    else {
        return 'background'.$matches[1].'url('.$matches[2].$dirUrl.'/'.$matches[3].$matches[4].')';
    }
 
}
function isImgUrl($imgUrl){
    return endWith($imgUrl,'.jpg') || endWith($imgUrl,'.jpeg') || endWith($imgUrl,'.gif') || endWith($imgUrl,'.png') || endWith($imgUrl,'.bmp');
}
function saveImgContent($imgUrl){
    global $domain;
    global $dirUrl;
    if(isImgUrl($imgUrl)){
        $imgContent = @file_get_contents($imgUrl);
        if(!empty($imgContent)){
            saveContent(public_path().'/html'.substr($imgUrl,strlen($domain)),$imgContent);
        }
    }
}
function saveImg($matches){
 
    global $domain;
    global $dirUrl;
    if (startWith($matches[2],'/')){
        $imgUrl = $domain.$matches[2];
    }
    else if(startWith($matches[2],'http://')){
        $imgUrl = $matches[2];
    }
    else {
        $imgUrl = $dirUrl.'/'.$matches[2];
    }
    saveImgContent($imgUrl);
    return '';
}
function saveBackImg($matches){
    global $domain;
    global $dirUrl;
    if (startWith($matches[3],'/')){
        $imgUrl = $domain.$matches[3];
    }
    else if(startWith($matches[3],'http://')){
        $imgUrl = $matches[3];
    }
    else {
        $imgUrl = $dirUrl.'/'.$matches[3];
    }
    saveImgContent($imgUrl);
    return '';
}
function ChuliJsImg($urls)
{
 
    global $domain;
    global $dirUrl;
    foreach($urls as $key=>$value){
 
 
        $jsContent = @file_get_contents($value);
        if(!stristr($jsContent,'<img') && !stristr($jsContent,'background')){
            continue;
        }
        preg_replace_callback('/<img(.*)src=["\']([^>]+)["\'](.*)\/?>/misU','saveImg',$jsContent);
        preg_replace_callback('/background(.*)url\((["\']?)([^>]+)(["\']?)\)/misU','saveBackImg',$jsContent);
    }
}
function saveContent($fullname,$content){
 
    if(!is_dir(dirname($fullname))) {
 
        mkdir(dirname($fullname), 0755, true);//这里true表示可以创建多级目录
    }
 
    //if(!file_exists($fullname)){
    $fp = @fopen($fullname,"w") or die("写文件失败");
    fwrite($fp,$content);
    fclose($fp);
    //}
 
}
function nullSetSring($str)
{
    if(empty($str)){
        return '';
    }
}
function nullSetArr($arr='')
{
    if(!is_array($arr)){
        if(empty($arr)){
            return '';
        }else{
            return $arr;
        }
    }
    foreach($arr as $key=>$value){
        $value =  nullSetArr($value);
        $arr[$key] = $value;
    }
    return $arr;
}
 
function existFullnameChangeName($fullname)
{
    $i=0;
    $pre_name = substr($fullname,0,strripos($fullname,'.'));
    $suff_name = strrchr($fullname,'.');
    while(file_exists($fullname)){
        $i++;
        $fullname = $pre_name.$i.$suff_name;
    }
    return $fullname;
}
 
function preSaveOrigUrl($orig_url, $request)
{
    global $domain;
    global $dirUrl;
    $domain = getDomainByUrl($orig_url);
    $dirUrl = getDirUrlByUrl($orig_url);
    $content = @file_get_contents($orig_url);
    if(empty($content)){
        return '-1';
    }
 
 
    $firstPath = getFirstDir($domain);
    $fullname = getFullFilename($orig_url, $domain);
 
    $charset = detectEncode($content);
    if($charset!='UTF-8'){
        $content = iconv($charset,'UTF-8',$content);
    }
    $content =str_ireplace('data-src','src',$content);
 
    $content = preg_replace_callback('/<link(.*)href=["\']([^>]+)["\'](.*)\/?>/misU','changeCss',$content);
    $content = preg_replace_callback('/<script([^>]*)src=["\']([^>]+)["\'](.*)>(.*)<\/script>/misU','changeJs',$content);
    $content = preg_replace_callback('/<img(.*)src=["\']([^>]+)["\'](.*)\/?>/misU','changeImg',$content);
    //处理延迟加载
 
    $content = preg_replace_callback('/<img(.*)data-original\s*=\s*["\']([^>]+)["\'](.*)\/?>/misU','changeDataOriginalImg',$content);
 
    $content = preg_replace_callback('/background(.*)url\((["\']?)([^>]+)(["\']?)\)/misU','changeBackImg',$content);
 
    //js 里面的图像
    preg_match_all('/<script([^>]*)src=["\']([^>]+)["\'](.*)>(.*)<\/script>/misU',$content,$out,PREG_PATTERN_ORDER);
    $jsUrls = $out[2];
 
    ChuliJsImg($jsUrls);
    //$fullname_script_name  = '/html/'.$firstPath.'/'.$fullname;
    $fullname = public_path().'/html/'.$firstPath.'/'.$fullname;
    //如果已经存在的话
    $fullname = existFullnameChangeName($fullname);
 
    $local_url = 'http://'.$request->server("HTTP_HOST").substr($fullname,strlen(public_path()));
 
    //抓取QQ网站好像有点问题
    //$content = str_replace("'qq.com'","'".$_SERVER['HTTP_HOST']."'",$content);
    //$content = str_replace('"qq.com"','"'.$_SERVER['HTTP_HOST'].'"',$content);
 
    return compact('fullname', 'content', 'local_url');
 
 
 
}
 
 
//史平忠的裁切功能  (只是裁切) //$fullImg 是原图像路径,$thumbImg 是新图像路径
//$fix 是为了适应伍佰灵的 没有作用  $width是新图宽度 $height 是新图高度
//最后参数一个wap  表示是否是从手机网站过来的
function thumbImgCut($fullImg, $width=114 , $height=76 ,$thumbImg,$defaultWidth='5000',$defaultHeight='5000', $fix=5, $copyheightbi='', $wap='')
{
    if(!is_file($fullImg)){
        //echo $fullImg ."不存在<br>\n";
        return ;
    }
 
    //list($w_src, $h_src) = getimagesize($fullImg);
    $imgInfo=getimagesize($fullImg);
    $w_src = $imgInfo[0];
    $h_src = $imgInfo[1];
    $imgType = $imgInfo[2];
    //first change small by rate
    if($width=='auto'){
        $width = $height * $w_src/$h_src;
        //假如自动的宽度大于默认宽度,就取默认宽度
        $width>$defaultWidth && $width = $defaultWidth;
    }
    if($height=='auto'){
        $height = $width * $h_src/$w_src;
        //假如自动的高度大于默认宽度,就取默认高度
        $height>$defaultHeight && $height = $defaultHeight;
    }
 
    $w_descFir    = $width;
    $h_descFir    = $height;
    $rate_descFir = $width/$height;
 
    $rate_old = $w_src/$h_src;
    //new rate >= old rate
    if ($rate_descFir >= $rate_old)
    {
 
        //切掉东西的方法
        $h_descFir = ceil($w_descFir / $rate_old);
    }
    //new rate < old rate
    else if ($rate_descFir < $rate_old)
    {
        //切掉东西的方法
        $w_descFir = ceil($h_descFir * $rate_old);
 
    }
    //source photo
    //gif
    if ($imgType==1)
    {
        $srcPho  = imagecreatefromgif($fullImg);
    }//jpeg(jpg)
    else if ($imgType==3)
    {
        $srcPho  = imagecreatefrompng($fullImg);
    }//其余假定为 jpeg 其实是$imgType==2
    else
    {
        $srcPho  = imagecreatefromjpeg($fullImg);
    }
    //first new small photo
    $descPhoFir = imagecreatetruecolor($w_descFir, $h_descFir);
    imagecopyresampled($descPhoFir, $srcPho, 0, 0, 0, 0, $w_descFir, $h_descFir, $w_src, $h_src);
    //second change small by crop
    if ($rate_descFir >= $rate_old)
    {
        $cropX  = 0;
        if(!empty($copyheightbi)){
            $copyheightbi = 1/$copyheightbi;
            $cropY =  ceil(($h_descFir-$height)/$copyheightbi);
        }else{   //假如没有 的话 就从减去的1/2 ;;;换句话说 就是只取中间,上下裁去相等
            $cropY =  ceil(($h_descFir-$height)/2);
        }
 
        $h_descFir = $height;
    }
    else if ($rate_descFir < $rate_old)
    {
        $cropX  = ceil(($w_descFir-$width)/2);
        $cropY =  0;
        $w_descFir = $width;
    }
    //second new small photo
    $descPhoSec = imagecreatetruecolor($width, $height);
    imagecopyresampled($descPhoSec, $descPhoFir, 0, 0, $cropX, $cropY, $width, $height, $width, $height);
    //生成gif
    if ($imgType==1)
    {
        imagegif($descPhoSec, $thumbImg);
    }//生成png
    else if ($imgType==3)
    {
        Imagepng($descPhoSec, $thumbImg);
    } //其余生成jpg(jpeg)
    else
    {
        $wap=='wap' ? $jingdu=90 : $jingdu=90;
        ImageJpeg($descPhoSec, $thumbImg, $jingdu);
    }
    @imagedestroy($photo);
 
    chmod($thumbImg, 0777);
}
 
//得到img指定的(大,或中或小)路径
//值有 auto 100 160 170 180 180_2 200 215 400
//这些值指的是自定义裁切的图的宽度
//最后参数一个wap  表示是否是从手机网站过来的
//最后参数一个wap  表示是否是从手机网站过来的
function getReferImg($litpic, $width='100', $height='100', $defautWidth='5000', $defaultHeight='5000',$copyheightbi='',$wap='')
{
    //error_reporting(0);
    //我们是先生成,再取出图片
    $pointPosition = strrpos($litpic, '.');
    $prevPath = substr($litpic,0,$pointPosition);
    $suffPath = strrchr($litpic, '.');
 
    //没有  $copyheightbi 即没有裁切点的时候
    if(empty($copyheightbi)){
        $newLitpic = $prevPath.'-'.$width.'-'.$height.$suffPath;
    }else{  //有裁切点的时候
        $newLitpic = $prevPath.'-'.$width.'-'.$height.'-'.$copyheightbi.$suffPath;
    }
 
 
    $newPicPath = $_SERVER['DOCUMENT_ROOT'].$newLitpic;
 
    //假如是手机网站的时候
    if($wap=='wap'){
        $newPicPath = $_SERVER['DOCUMENT_ROOT'].'/wap'.$newLitpic;
        if(!is_dir(dirname($newPicPath))){
            mkdirAll(dirname($newPicPath));
        }
    }
 
    //看是否存在这个裁剪的新图,有的话 就直接返回
    if(file_exists($newPicPath)){
        return $newLitpic;
    }
    $oldPicPath = $_SERVER['DOCUMENT_ROOT'].$litpic;
 
    thumbImgCut($oldPicPath,$width,$height,$newPicPath,$defautWidth,$defaultHeight,'5',$copyheightbi,$wap);
    return $newLitpic;
}
 
function isActiveRoute($currenRoote,$route, $output = "current")
{
 
    if ($currenRoote == $route) return $output;
    else return '';
}
 
function _getYaoQingMa($user_id)
{
    $miao = microtime();
    $weimiao_miao = explode(' ',$miao);
    $weimiao=$weimiao_miao[0];
    return date('YmdHis').'_'.substr($weimiao,2,6).'_'.$user_id;
}
 
?>
 


普通分类: