James
James

Reputation: 43647

Check is variable has this text

$check = array("this", "that", "to be", "not to be");

$yes = $no = array();

I'm trying to check, is each item of array $check contains text "be".

If it is, then add it to $yes, otherwise add to $no.

Seems I have to use a regular expression, can you please help me to compose it?

Upvotes: 1

Views: 145

Answers (2)

Gaurav
Gaurav

Reputation: 28755

foreach($array as $arr)
{
   if(in_array('be', explode(' ', $arr)) == true)  
      $yes[] = $arr;
   else
      $no[] = $arr;
}

Upvotes: 4

codaddict
codaddict

Reputation: 455030

If you want to look for the complete word be and not be as a substring you can use:

$check = array("this", "that", "to be", "not to be");
$yes = $no = array();
foreach($check as $v) {
        if(preg_match('/\bbe\b/',$v)) {
                $yes[] = $v;
        } else {
                $no[] = $v;
        }
}

Upvotes: 4

Related Questions