PHP 正则判断下字符串是否包含中文

| 选择喜欢的代码风格  

1. 判断是否包含中文字符(UTF-8)


<?php
function hasChinese($str) {
    return preg_match('/[\x{4e00}-\x{9fff}]/u', $str) === 1;
}

// 使用示例
$str1 = "Hello World";
$str2 = "你好 World";
$str3 = "こんにちは";

var_dump(hasChinese($str1)); // bool(false)
var_dump(hasChinese($str2)); // bool(true)
var_dump(hasChinese($str3)); // bool(false)

2. 更完整的中文字符范围(包含扩展区)


<?php
function hasChinese($str) {
    // 包含基本汉字、扩展A区、兼容汉字等
    return preg_match('/[\x{4e00}-\x{9fff}\x{3400}-\x{4dbf}\x{f900}-\x{faff}]/u', $str) === 1;
}

3. 判断是否全是中文


<?php
function isAllChinese($str) {
    return preg_match('/^[\x{4e00}-\x{9fff}]+$/u', $str) === 1;
}

// 使用示例
var_dump(isAllChinese("你好"));     // bool(true)
var_dump(isAllChinese("你好123"));   // bool(false)

4. 获取所有中文


<?php
function getChinese($str) {
    preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
    return $matches[0];
}

// 使用示例
$str = "Hello 你好 World 世界";
$chinese = getChinese($str);
print_r($chinese); // Array([0] => 你好 [1] => 世界)

5. 封装成通用函数


<?php
/**
 * 判断字符串是否包含中文
 * @param string $str 输入字符串
 * @param bool $strict 是否使用严格模式(包含扩展区)
 * @return bool
 */
function containsChinese($str, $strict = false) {
    if ($strict) {
        // 严格模式:包含基本汉字和扩展区
        $pattern = '/[\x{4e00}-\x{9fff}\x{3400}-\x{4dbf}\x{f900}-\x{faff}]/u';
    } else {
        // 普通模式:仅基本汉字
        $pattern = '/[\x{4e00}-\x{9fff}]/u';
    }
    return preg_match($pattern, $str) === 1;
}

// 测试
$testStrings = [
    "Hello",
    "你好",
    "?", // 扩展区汉字
    "Hello 你好",
    "123"
];

foreach ($testStrings as $str) {
    echo "$str: " . (containsChinese($str) ? "包含" : "不包含") . "中文\n";
    echo "$str (严格): " . (containsChinese($str, true) ? "包含" : "不包含") . "中文\n\n";
}

说明:

  • 使用 /u 修饰符:必须使用 UTF-8 模式处理 Unicode 字符
  • 字符范围说明:

    1. \x{4e00}-\x{9fff}:基本汉字(CJK统一表意文字)
    2. \x{3400}-\x{4dbf}:扩展A区
    3. \x{f900}-\x{faff}:兼容汉字

  • 性能考虑:如果只需要判断是否包含中文,使用 preg_match() 比 preg_match_all() 效率更高

 

CommandNotFound ⚡️ 坑否 - 其他频道扩展阅读:




发表评论