EDDYMENS

Published 2 years ago

PHP Check If String Contains

Table of contents

Check if a string contains a word (case sensitive)

01: <?php 02: 03: $word = "Golden"; 04: $sentence = "Silence is Golden"; 05: 06: if(strpos($sentence, $word) !== false){ 07: echo "Word exists"; 08: } else { 09: echo "Word does not exist"; 10: } 11: 12: ?>

The code above uses strpos to check for the position of $word in $sentence.

Do note that strpos can return 0 if the word is found in the first position. This is why the strict equality operator (!==) is used.

Check if a string contains a word (case insensitive)

01: <?php 02: 03: $word = "Golden"; 04: $sentence = "Silence is gOlDeN"; 05: 06: if(strpos(strtolower($sentence), strtolower($word)) !== false){ 07: echo "Word exists"; 08: } else { 09: echo "Word does not exist"; 10: } 11: 12: ?>

We use strtolower to make both strings lowercase. This way we can compare to see if the words are an exact match.

Check if a string contains a list of words (case sensitive)

01: <?php 02: 03: $words = ["Golden", 'Silence', 'Bronze']; 04: $sentence = "Silence is Golden"; 05: $splitSentence = explode(' ', $sentence); 06: $wordsFound = []; 07: 08: foreach($splitSentence as $wordInSentence) { 09: if(in_array($wordInSentence, $words)) { 10: $wordsFound[] = $wordInSentence; 11: } 12: } 13: 14: var_dump($wordsFound); //array(2) { [0]=> string(7) "Silence" [1]=> string(6) "Golden" } 15: 16: ?>

To check if the list of words can be found in the sentence, we first break up the sentence into an array of words.

With that, we then check to see if each word in the sentence can be found in the word list ie: $words using the foreach loop and in_array.

Check if a string contains a list of words (case insensitive)

01: <?php 02: 03: $words = array_map('strtolower', ["Golden", 'Silence', 'Bronze']); 04: $sentence = "Silence is gOlDeN"; 05: $splitSentence = explode(' ', $sentence); 06: $wordsFound = []; 07: 08: foreach($splitSentence as $wordInSentence) { 09: $lowerCasedWordInSentence = strtolower($wordInSentence); 10: if(in_array($lowerCasedWordInSentence, $words)) { 11: $wordsFound[] = $wordInSentence; 12: } 13: } 14: 15: var_dump($wordsFound); //array(2) { [0]=> string(7) "Silence" [1]=> string(6) "gOlDeN" } }

After converting the sentence into a word list, we use strtolower once again to convert each word to lowercase.

The same applies to the $words array. We use array_map to convert each word to lowercase.

With that, we use the foreach loop and in_array to check for words that match.

Here is another article you might like 😊 Prevent macOS from creating a .ds_store file