Check if string is just white space?

Php

Php Problem Overview


> 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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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

if (trim($str) == '')
{
 //string is only whitespace
}

Solution 3 - Php

if( trim($str) == "" )
    // the string is only whitespace

This should do the trick.

Solution 4 - Php

preg_match('/^\s*$/',$string)

change * to + if empty is not allowed

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJD IsaacksView Question on Stackoverflow
Solution 1 - PhpwebbiedaveView Answer on Stackoverflow
Solution 2 - PhpMANCHUCKView Answer on Stackoverflow
Solution 3 - PhpsvensView Answer on Stackoverflow
Solution 4 - PhpWrikkenView Answer on Stackoverflow