2

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 output 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;
}
homework
  • 4,987
  • 11
  • 40
  • 50

5 Answers5

7

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)
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • or `trim($string) == ''` might be slightly more efficient? – mpen Nov 14 '09 at 03:50
  • It might be; it depends on whether PHP stores the length of the string or if it null-terminates strings (I don't know which it uses). If it stores the length, both will perform about equally; if it uses null-terminated strings, performing a string comparison would probably be faster. – James McNellis Nov 14 '09 at 03:55
  • Well, if `strlen` performs equal or worse, it's better to go with the safer bet. Not that it really matters unless you're doing this 8 billion times. – mpen Nov 14 '09 at 04:32
  • I agree. I have to say, though, in terms of both elegance and raw performance, GZipp's answer is arguably the best of all the options presented on this page, by far. – James McNellis Nov 14 '09 at 05:56
7

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
GZipp
  • 5,386
  • 1
  • 22
  • 18
2
if ( trim($string) ) {
    // string contains text
}
else {
    // string contains only spaces or is empty
}
Galen
  • 29,976
  • 9
  • 71
  • 89
1

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.

jaywon
  • 8,164
  • 10
  • 39
  • 47
1

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

nandokakimoto
  • 1,361
  • 7
  • 14