Check if String Contains a Character in PHP

This tutorial will discuss about a unique way to check if string contains a character in php.

To check if a string contains a given character or not, we can use the strpos() function. It accepts a string as the first parameter and a substring as a second parameter. Then it returns the index position of the first occurrence of the given substring in the string, whereas, if the given substring does not exist in the string that it returns false.

Now to check if a String Contains a Character, we can pass the string as the first argument and character as a second argument in the strpos() function. If return value is not false, then it means the given character exists in the string.

We have created a separate function for this,

function stringContainsChar($str, $char)
{
    return strpos($str, $char) !== false;
}

It accept a string and character as an arguments, and returns true if the given character exists in the given string.

Let’s see the complete example,

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

$strValue = "Last Train";

$char = "s";

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

Output

The string contains the character.

Summary

We learned how to check if a string contains a character 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