澳门新葡萄京官网首页基于Snoopy的PHP近似完美获取网站编码的代码_php实例_脚本之家

先要到网络下载Snoopy.class.php
调用方法:
复制代码 代码如下:
require ‘lib/Snoopy.class.php’;
require ‘lib/WebCrawl.class.php’;//包罗下边代码
$go=new WebCrawl(”);
echo $go->getCharset();
?>

先要到互连网下载Snoopy.class.php 调用方法: 复制代码 代码如下: getCharset(卡塔尔国; ?> 复制代码 代码如下: url=$url; } //张开网址private function open { if($this->request!==null) {
if($this->request->status==200) { return true; } else { return
false; } } else { $this->request=new Snoopy();
$this->request->fetch; if($this->request->status==200) {
$this->request->results=strtolower($this->request->results);
$charset=$this->getCharset(); if { if($charset==”windows-1252″) {
$this->request->results=$this->uni_decode($this->request->results);
} else {
$this->request->results=mb_convert_encoding($this->request->results,”UTF-8″,$charsetState of Qatar;
} } return true; } else { return false; } } }
//获取网址title,keywords,description public function getWebinfo(卡塔尔国 {
$info=array( ‘title’=>”, ‘keywords’=>”, ‘desc’=>”,
‘ip’=>” 卡塔尔(قطر‎; if(!$this->open{return $info;exit;} //
print_r($this->request->results);exit; preg_match/si’,
$this->request->results, $titlematch ); if && is_array && count {
$info[‘title’] = strip_tags; } preg_match_all(‘//si’,
$this->request->results, $match); $ft=0; foreach {
if($mt==”keywords” || $mt==”description”) { $ft=1; } } if {
preg_match_all(‘//si’, $this->request->results, $match); if &&
is_array && count { $originals = $match[0]; $names = $match[2];
$values = $match[1]; if == count && count == count { $metaTags =
array(); for ($i=0, $limiti=count; $i < $limiti; $i++) {
$metaTags[$names[$i]] = array ( ‘html’ => htmlentities, ‘value’
=> $values[$i] ); } } } } else { if && is_array && count {
$originals = $match[0]; $names = $match[1]; $values = $match[2];
if == count && count == count { $metaTags = array(); for ($i=0,
$limiti=count; $i < $limiti; $i++) { $metaTags[$names[$i]] =
array ( ‘html’ => htmlentities, ‘value’ => $values[$i] ); } } }
} $result = array ( ‘metaTags’ => $metaTags );
if(isset($result[‘metaTags’][‘keywords’][‘value’])) {
$info[‘keywords’]=$result[‘metaTags’][‘keywords’][‘value’]; }
else { $info[‘keywords’]=””; }
if(isset($result[‘metaTags’][‘description’][‘value’])) {
$info[‘desc’]=$result[‘metaTags’][‘description’][‘value’]; }
else { $info[‘desc’]=””; } $domain=preg_replace(‘/http:///si’,
”, $this->url); $ip=@gethostbyname; $ip_arr=explode; if {
$info[‘ip’]=$ip; } return $info; } public function t {
for($i=0;$iopen{return false;exit;} //首先从html获取编码
preg_match(“/request->results,$temp) ? strtolower:””; if {
if(in_array($temp[1], $this->charset_arr)) { if {
$tmp_charset=$this->t($this->request->results,$temp[1]);
if($tmp_charset==$temp[1]) { return $temp[1]; } } else { return
$temp[1]; } } } if(!empty($this->request->headersState of Qatar卡塔尔(قطر‎ {
//从header中拿到编码
$hstr=strtolower(implode(“|||”,$this->request->headersState of Qatar卡塔尔;
preg_match(“/charset=[^w]?/is”,$hstr,$lang) ? strtolower:””; if {
return $lang[1]; } }
$encode_arr=array(“UTF-8″,”GB2312″,”GBK”,”BIG5″,”ASCII”,”EUC-JP”,”Shift_JIS”,”CP936″,”ISO-8859-1″,”JIS”,”eucjp-win”,”sjis-win”);
$encoded=mb_detect_encoding($this->request->results,$encode_arr);
if { return strtolower; } else { return false; } } } ?>

正文实例叙述了php截取html字符串及自动补全html标签的不二等秘书诀。共享给大家供我们参谋。具体解析如下:

复制代码 代码如下:
class WebCrawl
{
private $url;
private $request;
public $charset_arr=array(
‘gb2312’,
‘utf-8’,
‘big5’,
‘gbk’,
‘ascii’,
‘cp936’,
‘ibm037’,
‘ibm437’,
‘ibm500’,
‘asmo-708’,
‘dos-720’,
‘ibm737’,
‘ibm775’,
‘ibm850’,
‘ibm852’,
‘ibm855’,
‘ibm857’,
‘ibm00858’,
‘ibm861’,
‘ibm860’,
‘dos-862’,
‘ibm863’,
‘ibm864’,
‘ibm865’,
‘cp866’,
‘ibm869’,
‘ibm870’,
‘windows-874’,
‘cp875’,
‘shift_jis’,
‘ks_c_5601-1987’,
‘ibm1026’,
‘ibm01047’,
‘ibm01047’,
‘ibm01040’,
‘ibm01041’,
‘ibm01042’,
‘ibm01043’,
‘ibm01044’,
‘ibm01045’,
‘ibm01046’,
‘ibm01047’,
‘ibm01048’,
‘ibm01049’,
‘utf-16’,
‘unicodefffe’,
‘windows-1250’,
‘windows-1251’,
‘windows-1252’,
‘windows-1253’,
‘windows-1254’,
‘windows-1255’,
‘windows-1256’,
‘windows-1257’,
‘windows-1258’,
‘johab’,
‘macintosh’,
‘x-mac-japanese’,
‘x-mac-chinesetrad’,
‘x-mac-korean’,
‘x-mac-arabic’,
‘x-mac-hebrew’,
‘x-mac-greek’,
‘x-mac-cyrillic’,
‘x-mac-chinesesimp’,
‘x-mac-romanian’,
‘x-mac-ukrainian’,
‘x-mac-thai’,
‘x-mac-ce’,
‘x-mac-icelandic’,
‘x-mac-turkish’,
‘x-mac-croatian’,
‘x-chinese-cns’,
‘x-cp20001’,
‘x-chinese-eten’,
‘x-cp20003’,
‘x-cp20004’,
‘x-cp20005’,
‘x-ia5’,
‘x-ia5-german’,
‘x-ia5-swedish’,
‘x-ia5-norwegian’,
‘us-ascii’,
‘x-cp20261’,
‘x-cp20269’,
‘ibm273’,
‘ibm277’,
‘ibm278’,
‘ibm280’,
‘ibm284’,
‘ibm285’,
‘ibm290’,
‘ibm420’,
‘ibm423’,
‘ibm424’,
‘x-ebcdic-koreanextended’,
‘ibm-thai’,
‘koi8-r’,
‘ibm871’,
‘ibm880’,
‘ibm905’,
‘ibm00924’,
‘x-cp20936’,
‘x-cp20949’,
‘cp1025’,
‘koi8-u’,
‘iso-8859-1’,
‘iso-8859-2’,
‘iso-8859-3’,
‘iso-8859-4’,
‘iso-8859-5’,
‘iso-8859-6’,
‘iso-8859-7’,
‘iso-8859-8’,
‘iso-8859-9’,
‘iso-8859-13’,
‘iso-8859-15’,
‘x-europa’,
‘iso-8859-8-i’,
‘iso-2022-jp’,
‘csiso2022jp’,
‘iso-2022-jp’,
‘iso-2022-kr’,
‘x-cp50227’,
‘euc-jp’,
‘euc-cn’,
‘euc-kr’,
‘hz-gb-2312’,
‘gb18030’,
澳门新葡萄京官网首页,’x-iscii-de’,
‘x-iscii-be’,
‘x-iscii-ta’,
‘x-iscii-te’,
‘x-iscii-as’,
‘x-iscii-or’,
‘x-iscii-ka’,
‘x-iscii-ma’,
‘x-iscii-gu’,
‘x-iscii-pa’,
‘utf-7’,
‘utf-32’,
‘utf-32be’
);
public function __construct($url)
{
$this->url=$url;
}
//展开网址
private function open($url)
{
if($this->request!==null)
{
if($this->request->status==200)
{
return true;
}
else
{
return false;
}
}
else
{
$this->request=new Snoopy();
$this->request->fetch($url);
if($this->request->status==200)
{
$this->request->results=strtolower($this->request->results);
$charset=$this->getCharset();
if($charset!=”utf-8″)
{
if($charset==”windows-1252″)
{
$this->request->results=$this->uni_decode($this->request->results);
}
else
{
$this->request->results=mb_convert_encoding($this->request->results,”UTF-8″,$charset);
}
}
return true;
}
else
{
return false;
}
}
}
//获取网址title,keywords,description
public function getWebinfo()
{
$info=array(
‘title’=>”,
‘keywords’=>”,
‘desc’=>”,
‘ip’=>”
);
if(!$this->open($this->url)){return $info;exit;}
// print_r($this->request->results);exit;
preg_match(‘/

此间计算一下有关利用php截取html字符串自动补全html标签,实际花销中会平日遇上,非常多少人一直先strip_tags过滤掉html标签,不过就只剩余纯文本了,可读性很糟糕,上边是一个函数,代码如下:
复制代码 代码如下:/**
 * 截取HTML,并自行补全闭合
 * @param $html
 * @param $length
 * @param $end
 */
function subHtml($html,$length) {
 $result = ”;
 $tagStack = array();
 $len = 0;
 
 $contents = preg_split(“~(]+?>)~si”,$html,
-1,PREG_SPLIT_NO_EMPTY| PREG_SPLIT_DELIM_CAPTURE);
 foreach($contents as $tag)
 {
 if (trim($tag)==””)  continue;
 if(preg_match(“~]*?/>~si”,$tag)){
 $result .= $tag;
 }else
if(preg_match(“~([a-z0-9]+)[^/>]*?>~si”,$tag,$match)){
 if($tagStack[count($tagStack)-1] == $match[1]){
 array_pop($tagStack);
 $result .= $tag;
 }
 }else if(preg_match(“~]*?>~si”,$tag,$match)){
 array_push($tagStack,$match[1]);
 $result .= $tag;
 }else if(preg_match(“~~si”,$tag)){
 $result .= $tag;
 }else{
 if($len + mstrlen($tag) < $length){
 $result .= $tag;
 $len += mstrlen($tag); 
 }else {
 $str = msubstr($tag,0,$length-$len+1);
 $result .= $str;
 break;
 }
 
 }
 }
 while(!emptyempty($tagStack)){
 $result .= ”.array_pop($tagStack).’>’;
 }
 return  $result;
}
 
/**
 * 截取中文字符串
 * @param $string 字符串
 * @param $start 起始位
 * @param $length 长度
 * @param $charset  编码
 * @param $dot 附加字串
 */
function msubstr($string, $start, $length,$dot=”,$charset = ‘UTF-8’)
{
 $string = str_replace(array(‘&’, ‘”‘, ”,’ ‘), array(‘&’, ‘”‘, ”,’
‘), $string);
 if(strlen($string) <= $length) {
 return $string;
 }
 
 if(strtolower($charset) == ‘utf-8’) {
 $n = $tn = $noc = 0;
 while($n < strlen($string)) {
 $t = ord($string[$n]);
 if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
 $tn = 1; $n++;
 } elseif(194 <= $t && $t <= 223) {
 $tn = 2; $n += 2;
 } elseif(224 <= $t && $t <= 239) {
 $tn = 3; $n += 3;
 } elseif(240 <= $t && $t <= 247) {
 $tn = 4; $n += 4;
 } elseif(248 <= $t && $t <= 251) {
 $tn = 5; $n += 5;
 } elseif($t == 252 || $t == 253) {
 $tn = 6; $n += 6;
 } else {
 $n++;
 }
 $noc++;
 if($noc >= $length) {
 break;
 }
 }
 if($noc > $length) {
 $n -= $tn;
 }
 $strcut = substr($string, 0, $n);
 } else {
 for($i = 0; $i < $length; $i++) {
 $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i]
: $string[$i];
 }
 }
 
 return $strcut.$dot;
}
 
/**
 * 得到字符串的长度,包蕴中国和高丽国文。
 */
function mstrlen($str,$charset = ‘UTF-8’){
 if (function_exists(‘mb_substr’)) {
 $length=mb_strlen($str,$charset);
 } elseif (function_exists(‘iconv_substr’)) {
 $length=iconv_strlen($str,$charset);
 } else {
 preg_match_all(“/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/”,
$text, $ar);  
 $length=count($ar[0]);
 }
 return $length;
}
实例,代码如下:
复制代码 代码如下:* @param 要截取的HTML
$str
* @param 截取的数目 $num
* @param 是或不是供给增添愈来愈多 $more
* @return 截取串
*/
function phpos_chsubstr_ahtml($str,$num,$more=false)
{
    $leng=strlen($str);
      if($num>=$leng)
      return $str;
    $word=0;
    $i=0;                        /** 字符串指针 **/
    $stag=array(array());        /** 存放初阶HTML的标识 **/
    $etag=array(array());        /** 存放甘休HTML的标识 **/
    $sp = 0;
    $ep = 0;
      while($word!=$num)
      {
          if(ord($str[$i])>128)
          {
            //$re.=substr($str,$i,3);
            $i+=3;
            $word++;
          }
          else if ($str[$i]==’           {
              if ($str[$i+1] == ‘!’)
              {
                $i++;
                  continue;
              }
 
              if ($str[$i+1]==’/’)    
              {
                $ptag=&$etag ;
                $k=&$ep;
                $i+=2;
              }
              else                    
              {
                $ptag=&$stag;
                $i+=1;
                $k=&$sp;
              }
 
              for(;$i               {
                  if ($str[$i] == ‘ ‘)
                  {
                    $ptag[$k] = implode(”,$ptag[$k]);
                    $k++;
                      break;
                  }
                  if ($str[$i] != ‘>’) 
                  {
                    $ptag[$k][]=$str[$i];
                      continue;
                  }
                  else                
                  {
                    $ptag[$k] = implode(”,$ptag[$k]);
                    $k++;
                      break;
                  }
              }
            $i++;
              continue;
          }
          else
          {
            //$re.=substr($str,$i,1);
            $word++;
            $i++;
          }
      }
      foreach ($etag as $val)
      {
        $key1=array_search($val,$stag);
          if ($key1 !== false)          unset($stag[$key]);
      }
      foreach ($stag as $key => $val)
      {
          if (in_array($val,array(‘br’,’img’)))
unset($stag[$key1]);
      }
    array_reverse($stag);
    $ends = ”.implode(‘>’,$stag).’>’;
    $re = substr($str,0,$i).$ends;
      if($more)    $re.=’…’;
      return $re;
}
PHP截取字符串,生成文摘,大家在写BLOG时日常要求展现小说前有个别,可是又怕不刚巧截断破坏密闭标签以促成整个文档构造损坏,代码如下:
复制代码 代码如下:function
text_zhaiyao($text,$length卡塔尔国{ //文摘生成函数  $test:内容
$length:摘要长度
    global $Briefing_Length;
    mb_regex_encoding(“UTF-8”);
    if(mb_strlen($text) <= $length ) return $text;
    $Foremost = mb_substr($text, 0, $length);
    $re = ”    
(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|TABLE|TR|TD|TH|INPUT|SELECT|TEXTAREA|OBJECT|A|UL|OL|LI|
   
BASE|META|LINK|HR|BR|PARAM|IMG|AREA|INPUT|SPAN)[^>]*(>?)”;
    $Single = “/BASE|META|LINK|HR|BR|PARAM|IMG|AREA|INPUT|BR/i”;
     
    $Stack = array(); $posStack = array();
     
    mb_ereg_search_init($Foremost, $re, ‘i’);
     
    while($pos = mb_ereg_search_pos()){
    $match = mb_ereg_search_getregs();
    /* [Child-matching Formulation]:
     
    $matche[1] : A “/” charactor indicating whether current
“<…>” Friction is
    Closing Part
    $matche[2] : Element Name.
    $matche[3] : Right > of a “<…>” Friction
    */
    if($match[1]==””){
    $Elem = $match[2];
    if(mb_eregi($Single, $Elem) && $match[3] !=””){
    continue;
}

([^>]*)/si’, $this->request->results, $titlematch );
if (isset($titlematch) && is_array($titlematch) && count($titlematch)
> 0)
{
$info[‘title’] = strip_tags($titlematch[1]);
}
preg_match_all(‘/”]*)”?[s]*’ .
‘content=”?([^>”]*)”?[s]*[/]?[s]*>/si’,
$this->request->results, $match);
$ft=0;
foreach($match[1] as $mt)
{
if($mt==”keywords” || $mt==”description”)
{
$ft=1;
}
}
if($ft==0)
{
preg_match_all(‘/”]*)”?[s]*name=”?’ .
‘([^>”]*)”?[s]*[/]?[s]*>/si’,
$this->request->results, $match);
if (isset($match) && is_array($match) && count($match) == 3)
{
$originals = $match[0];
$names = $match[2];
$values = $match[1];
if (count($originals) == count($names) && count($names) ==
count($values))
{
$metaTags = array();
for ($i=0, $limiti=count($names); $i < $limiti; $i++)
{
$metaTags[$names[$i]] = array (
‘html’ => htmlentities($originals[$i]),
‘value’ => $values[$i]
);
}
}
}
}
else
{
if (isset($match) && is_array($match) && count($match) == 3)
{
$originals = $match[0];
$names = $match[1];
$values = $match[2];
if (count($originals) == count($names) && count($names) ==
count($values))
{
$metaTags = array();
for ($i=0, $limiti=count($names); $i < $limiti; $i++)
{
$metaTags[$names[$i]] = array (
‘html’ => htmlentities($originals[$i]),
‘value’ => $values[$i]
);
}
}
}
}
$result = array (
‘metaTags’ => $metaTags
);
if(isset($result[‘metaTags’][‘keywords’][‘value’]))
{
$info[‘keywords’]=$result[‘metaTags’][‘keywords’][‘value’];
}
else
{
$info[‘keywords’]=””;
}
if(isset($result[‘metaTags’][‘description’][‘value’]))
{
$info[‘desc’]=$result[‘metaTags’][‘description’][‘value’];
}
else
{
$info[‘desc’]=””;
}
$domain=preg_replace(‘/http:///si’, ”, $this->url);
$ip=@gethostbyname($domain);
$ip_arr=explode(“.”, $ip);
if(count($ip_arr)==4)
{
$info[‘ip’]=$ip;
}
return $info;
}
public function t($string,$o)
{
for($i=0;$i{
if(ord($string{$i})<128)
continue;
if((ord($string{$i})&224)==224)
{
//第三个字节判别通过
$char = $string{++$i};
if((ord($char)&128)==128)
{
//第3个字节推断通过
$char = $string{++$i};
if((ord($char)&128)==128)
{
$encoding = “UTF-8”;
break;
}
}
}
if((ord($string{$i})&192)==192)
{
//第多个字节推断通过
$char = $string{++$i};
if((ord($char)&128)==128)
{
//第1个字节推断通过
$encoding = “GB2312”;
break;
}
}
}
return strtolower($encoding);
}
function uni_decode ($str, $code = ‘utf-8’){
$str = json_decode(preg_replace_callback(‘/(d{5});/’,
create_function(‘$dec’, ‘return ‘\u’.dechex($dec[1]);’),
‘”‘.$str.'”‘));
if($code != ‘utf-8’){ $str = iconv(‘utf-8’, $code, $str); }
return $str;
}
//获取网址编码
public function getCharset()
{
if(!$this->open($this->url)){return false;exit;}
//首先从html获取编码
preg_match(“/request->results,$temp) ? strtolower($temp[1]):””;
if($temp[1]!=””)
{
if(in_array($temp[1], $this->charset_arr))
{
if($temp[1]==”gb2312″)
{
$tmp_charset=$this->t($this->request->results,$temp[1]);
if($tmp_charset==$temp[1])
{
return $temp[1];
}
}
else
{
return $temp[1];
}
}
}
if(!empty($this->request->headers))
{
//从header中获得编码
$hstr=strtolower(implode(“|||”,$this->request->headers));
preg_match(“/charset=[^w]?([-w]+)/is”,$hstr,$lang) ?
strtolower($lang[1]):””;
if($lang[1]!=””)
{
return $lang[1];
}
}
$encode_arr=array(“UTF-8″,”GB2312″,”GBK”,”BIG5″,”ASCII”,”EUC-JP”,”Shift_JIS”,”CP936″,”ISO-8859-1″,”JIS”,”eucjp-win”,”sjis-win”);
$encoded=mb_detect_encoding($this->request->results,$encode_arr);
if($encoded)
{
return strtolower($encoded);
}
else
{
return false;
}
}
}
?>

但愿本文所述对大家的php程序设计具备利于。

发表评论

电子邮件地址不会被公开。 必填项已用*标注