Checking substring in a string in PHP: Here, we will figure out how to check whether a word/substring exists in the string in PHP? Here, we will check a substring and furthermore print its record/position in the string.
Given a string and a word/substring, and we need to check whether a given word/substring exists in the string.
PHP code to check substring in the string:
<?php
//function to find the substring Position
//if substring exists in the string
function findMyWord($s, $w) {
if (strpos($s, $w) !== false) {
echo 'String contains ' . $w . '<br/>';
} else {
echo 'String does not contain ' . $w . '<br/>';
}
}
//Run the function
findMyWord('The Quick brown fox jumps right over the Lazy Dog', 'fox');
findMyWord('The Quick brown fox jumps right over the Lazy Dog', 'hello');
?>
Output:
String contains fox
String does not contain hello
Clarification:
To check if a string contains a word (or substring) we utilize the PHP strpos() function. We check if the word ($w) is available in the String ($s). Since strpos() additionally returns a non-Boolean value which assesses to bogus, We need to check the condition to be unequivocal !== bogus (Not equivalent to False) Which guarantees that we get an increasingly solid reaction.