Checking string for whitespace
Is there a way I can check for whitespace?
For example, I DO NOT want to check for whitespace such as this...$string = "The dog ran away!";
and have it output Thedogranaway!
I want to check if there if the entry is ALL whitespace and whitespace only? ...and have it o开发者_如何转开发utput the error!
Basically, I don't want to be able to enter all whitespace, and still have it do the mysql_query.
Also, is there a way I can strip all the whitespace before the string, and not from the rest of the string?$string = " "WHITESPACE HERE" The dog ran away!";
if(empty($string) OR $string == " "){ // crappy example of what i'm trying to do
echo "Try again, please enter a message!"; // error
} else {
mysql_query("UPDATE users SET mesg='$string'")or die(mysql_error()); // do something
echo $post;
}
There is also ctype_space (the easiest, imo, and made to do just this, without doing a bunch of unnecessary string manipulation):
$str = " \r\n \t ";
if (ctype_space($str)) {
echo 'All whitespace';
}
// All whitespace
How about:
if (strlen(trim($string)) == 0)
or, the possibly more efficient:
if (trim($string) == '')
or, you could use a regular expression:
if (preg_match("/^\s+$/", $string) != 0)
if ( trim($string) ) {
// string contains text
}
else {
// string contains only spaces or is empty
}
Maybe you are looking for a trim() method. In Java it would be String.trim(). I don't know how it should looks like in php, however this link might help http://php.net/manual/en/function.trim.php
You can use the trim() function on an empty string:
if (strlen(trim($string)) == 0){
//do something
}else{
// do something else
}
To trim leading white space:
ltrim($string)
In the previous example " This is text"
would return "This is text". Also trim() would achieve the same result, but trim() removes whitespace before and after the string.
精彩评论