<?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
Explanation:
To check if a string contains a word (or substring) we use the PHP strpos() function. We check if the word ($w) is present in the String ($s). Since strpos() also returns non-Boolean value which evaluates to false, We have to check the condition to be explicit !== false (Not equal to False) Which ensures that we get a more reliable response.
PHP code to check substring in the string
Output
Explanation:
To check if a string contains a word (or substring) we use the PHP strpos() function. We check if the word ($w) is present in the String ($s). Since strpos() also returns non-Boolean value which evaluates to false, We have to check the condition to be explicit !== false (Not equal to False) Which ensures that we get a more reliable response.
need an explanation for this answer? contact us directly to get an explanation for this answer