How to Check if a String Contains a Specific Word or Substring in PHP

The string comparison can be easily done by the PHP built-in function called strpos(). The strpos() function in PHP, is the easiest way to check if a string contains a specific word or substring. The strpos() function finds the position of the first occurrence of a substring in a string. It returns the position if the string is found, otherwise returns FALSE.

Using the strpos() function, you can check if a string contains a specific word or character, or substring in PHP.

The following example code snippet checks whether a specific word exists in the given string.

$string "Welcome to codexworld, the world of programming.";
$word  "codexworld";

if(
strpos($string$word) !== false){
    echo 
"The word '$word' was found in the given string";
}else{
    echo 
"The word '$word' was not found in the given string";
}

The following example code snippet checks whether a specific substring exists in the given string.

<?php
$string 
"Welcome to codexworld, the world of programming.";
$substring "the world";

if(
strpos($string$substring) !== false){
    echo 
"The substring '$substring' was found in the given string";
}else{
    echo 
"The substring '$substring' was not found in the given string";
}

The strpos() function is case-sensitive, use the stripos() function for case-insensitive comparison in PHP.

Leave a reply

keyboard_double_arrow_up