【问题标题】:PHP - How to ignore numbers/numeric on string using explode() or preg_split() functionPHP - 如何使用explode()或preg_split()函数忽略字符串上的数字/数字
【发布时间】:2019-06-16 18:00:23
【问题描述】:

我想让explode 或preg_split 函数忽略数字/数字。

$string = "my name is numbre 9000 900 1";

$dictionary = array("my", "name", "is", "number");

$words = explode(' ',$string);

foreach($words as $wrd):

if(in_Array($wrd, $dictionary)){
  echo $wrd;
}
elseif(in_Array($wrd, $dictionary) == FALSE){
  echo $wrd."->wrong";
}

我想要的输出应该是:

my
name
is
numbre<-wrong
9000
900
1

不是:

my
name
is
numbre<-wrong
9000<-wrong
900<-wrong
1<-wrong

知道我该怎么做吗?

【问题讨论】:

  • 检查每个单词是否在您的字典中 is_numeric.
  • 您的预期和实际&lt;-wrong 之间有什么区别?您的标题与您提供的示例不完全匹配,这使您的问题有些混乱。

标签: php explode preg-split


【解决方案1】:

正如评论中提到的,您可以使用或|| 来检查字符串是否为is_numeric

请注意,您的代码可能会更短:

$string = "my name is numbre 9000 900 1";
$dictionary = array("my", "name", "is", "number");
foreach(explode(' ',$string) as $wrd){
    if(in_array($wrd, $dictionary) || is_numeric($wrd)){
        echo $wrd . PHP_EOL;
    } else {
        echo $wrd."->wrong" . PHP_EOL;
    }
}

结果:

my
name
is
numbre->wrong
9000
900
1

查看php demo

【讨论】:

    【解决方案2】:

    您的原始方法很好,我们会对其稍作修改并应用preg_split。在这里,我们首先检查is_numeric,如果TRUE 我们continue,然后我们array_search 我们的字典,如果FALSE 我们附加-&gt;wrong,否则我们continue

    测试

    $str = "my name is numbre 9000 900 1 and some other undesired words";
    $dictionary = array("my", "name", "is", "number");
    $arr = preg_split('/\s/', $str);
    
    foreach ($arr as $key => $value) {
        if (is_numeric($value)) {
            continue;
        } elseif (array_search($value, $dictionary) === false) {
            $arr[$key] = $value . "->wrong";
        } else {
            continue;
        }
    }
    
    var_dump($arr);
    

    输出

    array(12) {
      [0]=>
      string(2) "my"
      [1]=>
      string(4) "name"
      [2]=>
      string(2) "is"
      [3]=>
      string(13) "numbre->wrong"
      [4]=>
      string(4) "9000"
      [5]=>
      string(3) "900"
      [6]=>
      string(1) "1"
      [7]=>
      string(10) "and->wrong"
      [8]=>
      string(11) "some->wrong"
      [9]=>
      string(12) "other->wrong"
      [10]=>
      string(16) "undesired->wrong"
      [11]=>
      string(12) "words->wrong"
    }
    

    RegEx Demo

    【讨论】:

    • Hardcoding if ($value === 'numbre') 似乎遗漏了代码的一个要点,即根据字典检查单词。
    猜你喜欢
    • 2011-03-16
    • 2013-10-05
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2012-08-08
    • 1970-01-01
    相关资源
    最近更新 更多