Reputation: 11
I want to make explode or preg_split function to ignore numbers/numeric.
$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";
}
the output I want should be:
my
name
is
numbre<-wrong
9000
900
1
not:
my
name
is
numbre<-wrong
9000<-wrong
900<-wrong
1<-wrong
any idea how do I do this?
Upvotes: 0
Views: 404
Reputation: 27743
Your original method is just fine, we'd slightly modify that and apply the preg_split
. Here, we check first for is_numeric
, if TRUE
we continue
, then we array_search
our dictionary, if FALSE
we append ->wrong
, otherwise we 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"
}
Upvotes: 2
Reputation: 163457
As mentioned in the comment, you could use an or ||
to check if the string is_numeric.
Note that you might write your code a bit shorter:
$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;
}
}
Result:
my
name
is
numbre->wrong
9000
900
1
See a php demo
Upvotes: 2