在PHP(UTF-8或Windows-1256)中检测字符串的字符集


Detect charset of string in PHP (UTF-8 or Windows-1256)


我正在编写基于"SimpleHTMLDOM"的脚本,我想在获取URL的内部文本后检测字符串的字符集,并使用iconv()将其转换为"UTF-8">
我尝试了很多东西,但没有一个能用Windows-1256
我尝试过的:-

mb_detect_encoding($content)Windows-1256检测为UTF-8
mb_detect_encoding($content, "windows-1256")给出错误Illegal argument

function is_utf8($string) {   
  return preg_match('%^(?:  
  ['x09'x0A'x0D'x20-'x7E] # ASCII  
  | ['xC2-'xDF]['x80-'xBF] # non-overlong 2-byte  
  | 'xE0['xA0-'xBF]['x80-'xBF] # excluding overlongs  
  | ['xE1-'xEC'xEE'xEF]['x80-'xBF]{2} # straight 3-byte  
  | 'xED['x80-'x9F]['x80-'xBF] # excluding surrogates  
  | 'xF0['x90-'xBF]['x80-'xBF]{2} # planes 1-3  
  | ['xF1-'xF3]['x80-'xBF]{3} # planes 4-15  
  | 'xF4['x80-'x8F]['x80-'xBF]{2} # plane 16  
  )*$%xs', $string);
}

如果不是UTF-8,此函数将返回"0",但如果字符串是UTF-8,则返回"找不到页面"。我不知道为什么
我的代码是:

$html = file_get_html($url);
foreach($html->find('div[id=content]') as $element) {
  $content = $element->innertext;
  #Detect charset encoding of $content
}

我正在使用的URL:
UTF-8:http://www.masrawy.com/news/Egypt/Politics/2013/March/3/5541050.aspx
Windws-1256:http://www.youm7.com//News.asp?NewsID=965545

您尝试过使用吗

function is_utf8($string) {
  return (mb_detect_encoding($string, 'UTF-8', true) == 'UTF-8');
}

这对我在你指定的URL上有效。

此外,我让masrawy.com网站在测试一些不同的选项时始终无法加载(也许是你可能会看到"找不到页面"的原因(。。。

奇怪的是,试图像你一样使用正则表达式导致PHP在我的Windows安装中完全自杀,并导致Apache崩溃。

这是根据Mark答案和我在之前使用的函数的整个函数

function utf8($utf8){   
if(mb_detect_encoding($string,'UTF-8',true) =='UTF-8'); 
return $utf8; else 
$utf8=iconv("windows-1256","utf-8",$utf8);
return $utf8;
  }

要使用它,只需调用函数,它就会返回正确的值。

utf8($text)