gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:04:11 25 4
gpt4 key购买 nike


我正在处理基于“Simple HTML DOM”的脚本,我想在获取 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
}

我正在使用的网址:
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 也随之崩溃。

关于php - 检测 PHP 中字符串的字符集(UTF-8 或 Windows-1256),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15188509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com