Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is just white space? [duplicate]

Tags:

php

Possible Duplicate:
If string only contains spaces?

I do not want to change a string nor do I want to check if it contains white space. I want to check if the entire string is ONLY white space. What the best way to do that?

like image 223
JD Isaacks Avatar asked Jun 07 '10 19:06

JD Isaacks


People also ask

How do I check if a string is just whitespace?

Python String isspace() The isspace() method returns True if there are only whitespace characters in the string. If not, it return False.

How do you check if string is empty or has only spaces in it using Python?

Python String isspace() is a built-in method used for string handling. The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters such as: ' ' – Space.

How do you check for space in regex?

The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is same as [ \t\n\r].


2 Answers

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

like image 99
webbiedave Avatar answered Sep 28 '22 21:09

webbiedave


since trim returns a string with whitespace removed, use that to check

if (trim($str) == '') {  //string is only whitespace } 
like image 29
MANCHUCK Avatar answered Sep 28 '22 19:09

MANCHUCK