Q:

PHP | Check whether a specific word/substring exists in a string

belongs to collection: PHP String Programs

0

Given a string and a word/substring, and we have to check whether a given word/substring exists in the string.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

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

total answers (1)

PHP | Reverse a given string without using the lib... >>
<< PHP program to convert string to lowercase without...