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

$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.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.