PHP-如何使用explode()或preg_split()函数忽略字符串上的数字/数字

时间:2019-06-16 18:00:23

标签: php explode preg-split

我想使用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

你知道我该怎么做吗?

2 个答案:

答案 0 :(得分:2)

您的原始方法很好,我们将对其稍加修改并应用preg_split。在这里,我们首先检查is_numeric,如果TRUE我们continue,那么我们array_search我们的字典,如果FALSE我们附加->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

答案 1 :(得分:2)

如评论中所述,您可以使用or或||来检查字符串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