in Software Development #PHP

Check if a string contains a character with PHP

Checking if a string contains a character could be accomplished easily with a regular expression or you can use the built-in PHP functions.

To check if a string contains a character of a specific case you can use strpos.

$haystack = 'This is my haystack that we shall check'
$has_A = strpos($haystack, 'A') !== false;
$has_a = strpos($haystack, 'a') !== false;

And if you happen to not care about the character's case, you can use stripos.

$has_a = stripos($haystack, 'a') !== false;

The strpos functions return the numeric position of the character. If it can't find the character, it will return a boolean false (hence the ===).

These functions can also work with strings of two or more character and not limited to just a single character at a time.