Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Find if a string contains only whitespaces and nothing else

Tags:

php

How do I find out if a string contains ONLY whitespaces and nothing else? The number of such spaces does not matter.

if () // $string contains ONLY whitespaces and nothing else   
{
// do something
}

Best if can provide a solution that can be generalised to any character: How do I find if a string contains ONLY some character and nothing else

like image 542
forgodsakehold Avatar asked Jan 01 '26 15:01

forgodsakehold


1 Answers

A non-regex approach could be:

if(strlen($string) >= 1 && empty(trim($string))) {

empty(trim($string)) removes all whitespace then checks if the string is empty. strlen($string) >= 1 confirms the string wasn't empty to start with. If empty strings are also allowed that check can be removed.

like image 106
chris85 Avatar answered Jan 03 '26 06:01

chris85



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!