Home » PHP » PHP Examples

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

<?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.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




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


© https://www.includehelp.com some rights reserved.