Check if a string contains a character with PHP

Josh Sherman
1 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles