Check if String Contains SubString (Case Insensitive) in PHP

This tutorial will discuss how to check if string contains substring (case insensitive) in PHP.

To check if a string contains a substring in a case-insensitive manner in PHP, we can use the stripos() function.

The stripos() function accepts two strings as arguments i.e. a string and a subString. It returns the index position of the first occurrence of a case-insensitive substring within the given string. If the substring does not exist in the string, it will return false.

We have created a separate function for this purpose.

function contains($strValue, $substring)
{
    return stripos($strValue, $substring) !== false;
}

It accepts a string and a substring as arguments and uses the stripos() function to check if the string contains the given substring irrespective of case. If stripos() returns a non-false value, it means the substring is found in the string.

An important point to note is that, this function performs a case-insensitive search, meaning it will try to match the substring regardless of uppercase or lowercase characters.

Let’s see the complete example,

<?php
/**
 * Check if a string contains a substring (case-insensitive).
 *
 * @param string $strValue The string to validate.
 * @param string $substring The substring to search for.
 * @return bool True if the string contains the substring
 *              (case-insensitive), false otherwise.
 */
function contains($strValue, $substring)
{
    return stripos($strValue, $substring) !== false;
}

// Example usage:
$strValue = 'This is some RANDOM Text';
$substring = 'random';

if (contains($strValue, $substring)) {
    echo "The string contains the substring '$substring'.";
} else {
    echo "The string does not contain the substring '$substring'.";
}
?>

Output

The string contains the substring 'random'.

Summary

Today, we learned how to check if string contains substring (case insensitive) 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