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

Learn, how to check whether a word/substring exists in the string in PHP? Here, we will check a substring and also print its index/position in the string.
Submitted by Bhanu Sharma, on August 10, 2019 [Last updated : March 13, 2023]

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

PHP code to check whether a specific word/substring exists in a 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.

PHP String Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.