「说技术」 PHP如何从字符串中过滤出中文
实现目标
输入字符串:”012\x99 走过的路,不要再走”,处理后,只保留汉字 “走过的路不要再走”
实现过程
1、从 utf-8 字符编码转化为 GB2312 多字节编码
2、GB2312汉字编码范围 [xb0-xf7][xa0-xfe],每两个字节形成一个中文字符
3、使用 PHP 字节操作函数 unpack 提取字符的二进制
4、提取出中文字符
PHP 代码
/**
* 过滤出一句话中的中文字符
*
* @param string $sentence
* @return string
*/
public function filterGB2312Words($sentence)
{
$filterWords = '';
for ($i = 0, $iMax = mb_strlen($sentence); $i < $iMax; $i++) {
$wordUtf8 = mb_substr($sentence, $i, 1);
$wordGb2312 = iconv('utf-8', 'gb2312//IGNORE', $wordUtf8);
if (strlen($wordGb2312) < 2) {
// 不是中文, 跳过
continue;
}
$byte1 = unpack('C', $wordGb2312, 0)[1];
$byte2 = unpack('C', $wordGb2312, 1)[1];
// https://www.wenjiangs.com/group/topic-19158.html
// GB2312汉字: [xb0-xf7][xa0-xfe]
if (($byte1 >= ord("\xb0") && $byte1 <= ord("\xf7")) && ($byte2 >= ord("\xa0") && $byte2 <= ord("\xfe"))) {
$filterWords .= $wordUtf8;
}
}
return $filterWords;
}
/**
* 测试过滤中文字符,忽略半角或英文字符
*
* @return void
*/
public function testGB2312Words()
{
$sentence = "012\x99 走过的路,不要再走";
$result = $this->filterGB2312Words($sentence);
$this->assertEquals('走过的路不要再走', $result);
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: