Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strpos with two words to find

Tags:

php

strpos

I found this example on stackoverflow:

if (strpos($a,'are') !== false) {
    echo 'true';
}

But how do I make it search for two words. I need something like this: if $a contains the words "are" or "be" or both echo "contains";

I tried xor and ||

like image 680
10now Avatar asked Mar 01 '13 14:03

10now


2 Answers

Just check both words separately and use the boolean or-operator to check if either one or both are contained in $a:

if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
  echo "contains";
}

Note that due to the or-operator, the second check (for 'be') is not performed if the first one already showed that $a contains 'are'.

like image 178
Veger Avatar answered Oct 21 '22 15:10

Veger


An alternative: Searches any length of words in the longer string.

Since you've haven't picked an answer from all the strpos answers (most of which should work with just two words, try this function of mine which exceeds word limits. It can find any varying length of words from the longer string (but doesn't use strpos). I think with strpos, you would have to know the number of words to determine how many || you should use or make use of a loop (sort of). This method eliminates all that and gives you a more flexible way to reuse your codes. I thinks codes should be flexible, reusable and dynamic. Test it and see if it does what you want!

function findwords($words, $search) {
    $words_array = explode(" ", trim($words));
    //$word_length = count($words_array);

    $search_array = explode(" ", $search);
    $search_length = count($search_array);

    $mix_array = array_intersect($words_array, $search_array);
    $mix_length = count($mix_array);

    if ($mix_length == $search_length) {
        return true;
    } else {
        return false;
    }
}



 //Usage and Examples

    $words = "This is a long string";
    $search = "is a";

    findwords($words, $search);

    // $search = "is a"; // returns true
    // $search = "is long at"; // returns false
    // $search = "long"; // returns true
    // $search = "longer"; // returns false
    // $search = "is long a"; // returns true
    // $search = "this string"; // returns false - case sensitive
    // $search = "This string"; // returns true - case sensitive
    // $search = "This is a long string"; // returns true
like image 5
Steward Godwin Jornsen Avatar answered Oct 21 '22 16:10

Steward Godwin Jornsen