是否可以检查数组中的单词是否包含非英文字符


is it possible to check whether a word in an array contains a non-english character

我正在点击此链接 删除非英文字符 PHP

但是我仍然想知道是否可以检查数组中的单词是否包含非英语字符。

谢谢!

要几乎完全复制粘贴其他线程的答案,您只需使用 preg_match

$foundNonEnglishCharacter = false;
foreach ($words as $word) {
    if (preg_match('/[^'00-'255]/', $word)) {
        $foundNonEnglishCharacter = true;
        break;
    }
}
var_dump($foundNonEnglishCharacter); //If true, there's a non-english character somewhere - if not, then there's no english characters.

正则表达式尸检:

[^'00-'255] - 不在 ASCII 值 0 到 255 范围内的任何字符(因此,如果有任何匹配,它确实包含此范围之外的字符)

您可以在 asciitable.com 上找到常规的 0-255 ascii 值及其含义

正如我在这里的评论中所建议的那样,您可以将array_filter()与回调函数一起使用来返回非英语单词。请注意,这使用 h2ooooooo 答案中提供的正则表达式:

$result = array_filter($array, function($word) { 
    return preg_match('/[^'00-'255]/', $word); 
});

现在,$result将是一个包含所有非英语单词的数组。如果您尝试检查数组中是否包含任何包含非英语字符的单词,则可以使用 count() 检查 $result 数组中的元素数:

if (count($result) > 0) {
    // at least a word containing non-English characters 
    // found in the array
}

是的。这是可能的。

使用删除非英文字符 PHP。

$strNew = preg_replace('/[^'00-'255]+/u', '', $str);
if($strNew == $str) {
    // all english
} else {
    // non-english character
}