How can i check to see if a string only contains spaces?
To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 . If the string has a length of 0 after calling the trim method, then the string contains only spaces.
Python isspace() method is used to check space in the string. It returna true if there are only whitespace characters in the string. Otherwise it returns false. Space, newline, and tabs etc are known as whitespace characters and are defined in the Unicode character database as Other or Separator.
PHP | ctype_space() Function A ctype_space() function in PHP is used to check whether each and every character of a string is whitespace character or not. It returns True if the all characters are white space, else returns False.
if (strlen(trim($str)) == 0)
or if you don't want to include empty strings,
if (strlen($str) > 0 && strlen(trim($str)) == 0)
from: https://stackoverflow.com/a/2992388/160173
This will be the fastest way:
$str = ' '; if (ctype_space($str)) { }
Returns false
on empty string because empty is not white-space. If you need to include an empty string, you can add || $str == ''
This will still result in faster execution than regex or trim.
ctype_space
as a function:
function stringIsNullOrWhitespace($text){ return ctype_space($text) || $text === "" || $text === null; }
echo preg_match('/^ *$/', $string)
Should work.
check if result of trim() is longer than 0
Use a regular expression:
$result = preg_match('/^ *$/', $text);
If you want to test for any whitespace, not just spaces:
$result = preg_match('/^\s*$/', $text);
I think using regexes is overkill, but here's another sol'n anyway:
preg_match('`^\s*$`', $str)
another way
preg_match("/^[[:blank:]]+$/",$str,$match);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With