0

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?

2
  • Check if each word is in your dictionary or is_numeric. Commented Jun 16, 2019 at 18:05
  • what is the difference between you expected and actual <-wrong? your title doesn't really match the example you gave and that made your question a bit confusing. Commented Jun 16, 2019 at 18:36

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Test

$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);

Output

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 Comment

Hardcoding if ($value === 'numbre') seems to miss a main point of the code which is to check the words against the dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.