Check if String Contains a SubString in PHP

This tutorial will discuss about a unique way to check if string contains a substring in PHP.

To check if string contains a given substring in PHP we can use the strpos() function. It accept a string as the first argument and is substring as a second argument, and returns the index position of the first occurrence of the given substring in the string. If the given substring does not exist in the string then it returns false.

So, we can use this strpos() function to check if a given string contains a substring or not.

We have created a separate function for this,

function containsSubstring($str, $substring)
{
    return strpos($str, $substring) !== false;
}

It accepts a string and a substring as arguments and returns true if the given string contains the given substring.

Let’s see the complete example,

<?php
/**
 * Checks if a string contains a specific substring using strpos().
 *
 * @param string $str The string to check.
 * @param string $substring The substring to look for in the string.
 * @return bool True if the string contains the substring, false otherwise.
 */
function containsSubstring($str, $substring)
{
    return strpos($str, $substring) !== false;
}

$strValue = "Last Coder is Here";
$substring = "Coder";

// Check if string contains a given substring
if (containsSubstring($strValue, $substring)) {
    echo "The string contains the given substring.";
} else {
    echo "The string does not contain the given substring.";
}
?>

Output

The string contains the given substring.

Summary

We learned about a way to check if a string contains a substring in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top