0

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

2 Answers 2

5

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)...

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

Comments

1

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.

2 Comments

The user doesn't even know that he should do a sub-foreach. This answer is not really helping him at all...
what are you, his mother? I'm sure he can decide for himself if it's helping him or not. Your advice is more detailed and gets you more points. I would argue that since my answer isn't "wrong" casing down votes on it is just petty. Furthermore, if my answer leads him to discover regular expressions I will have taught him to fish compared to your handing him a fish stick.

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.