我想使用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
你知道我该怎么做吗?
答案 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"
}
答案 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