user1038814
user1038814

Reputation: 9677

searching for a sub string in an array in php

I'm trying to search for the occurrence of certain words in a string and match them with a short list in an array. I'll explain my question by means of an example.

            $arrTitle = explode(" ", "Suburban Apartments");
    foreach( $arrTitle as $key => $value){
        echo "Name: $key, Age: $value <br />";
        $words = array("hotel", "apart", "hostel");
        if (in_array($value, $words)) {
            echo "Exists";
        }
    }

I wish to compare a part of the string, in the above example 'Apartments' against the $words array for the occurrence of the string 'Apart'ments. I hope this makes sense. Is this possible at all?

Thanks

Upvotes: 0

Views: 124

Answers (2)

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

Then you'll have to change a bit your code. Look at this below:

$arrTitle = explode(" ", "Suburban Apartments");
foreach( $arrTitle as $key => $value){
    echo "Name: $key, Age: $value <br />";
    $words = array("hotel", "apart", "hostel");
    foreach($words as $word){
        if (stripos($value, $word) !== false) {
            echo "Exists";
        }
    }
}

Note the added foreach on the words to search and the in_array replacement for strpos.

For your personnal information, in_array checks if the $word is in the array as a whole value, which is not what you wanted. You need to check for the existence of each word using strpos or stripos (case insensitive)...

Upvotes: 5

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28439

Use regular expressions to match the text.

http://php.net/manual/en/function.preg-match.php

You'll need to cycle through each of your sought array values one at a time so you'll have to loop inside your loop and run the regexp on each one looking for a match.

Make sure to make them case insensitive.

Upvotes: 1

Related Questions