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

Checking substring in a string in PHP: Here, we are going to 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

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 substring in the string


//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');


String contains fox
String does not contain hello


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



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.