【问题标题】:is it possible to check whether a word in an array contains a non-english character [duplicate]是否可以检查数组中的单词是否包含非英文字符[重复]
【发布时间】:2013-12-18 12:37:15
【问题描述】:

我正在关注此链接Remove Non English Characters PHP

但我仍然想知道是否可以检查 array 中的单词是否包含非英语字符。如果是的话。如何?

谢谢!

【问题讨论】:

  • 您对所链接问题的答案有什么不明白的地方?
  • preg_match 而不是 preg_replace?

标签: php


【解决方案1】:

要几乎完全复制粘贴另一个线程的答案,您可以使用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 值以及它们的含义

【讨论】:

  • 好一个'正则表达式尸检':))
  • 感谢您的回答。我可以实现它来检查数组中的单词吗?
  • @RishabhRaj:使用array_filter$new = array_filter($array, function($word) { return preg_match('/[^\00-\255]/', $word); });
  • @AmalMurali 将其作为答案发布,我会接受 :)
  • @RishabhRaj 检查我的编辑 - 它只是用循环替换它。
【解决方案2】:

正如我suggested in a comment here,您可以使用array_filter() 和回调函数来返回非英语单词。请注意,这使用了h2ooooooo's answer中提供的正则表达式:

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

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

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

【讨论】:

    【解决方案3】:

    是的。有可能的。

    使用Remove Non English Characters PHP

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多