Tony Stark
Tony Stark

Reputation: 25538

regular expression to match an empty (or all whitespace) string

i want to match a string that can have any type of whitespace chars (specifically I am using PHP). or any way to tell if a string is empty or just has whitespace will also help!

Upvotes: 8

Views: 27582

Answers (7)

lsblsb
lsblsb

Reputation: 1352

The following regex checks via lookahead and lookbehind assertion, if the string contains whitespace at the beginning or at the end or if the string is empty or contains only whitespace:

/^(?!\s).+(?<!\s)$/i

invalid (inside "):

""
" "
" test"
"test "

valid (inside "):

"t"
"test"
"test1 test2"

Upvotes: 0

Emre Yazici
Emre Yazici

Reputation: 10174

if(preg_match('^[\s]*[\s]*$', $text)) {
    echo 'Empty or full of whitespaces';
}

^[\s]* means the text must start with zero or more whitespace and [\s]*$ means must end with zero or more whitespace, since the expressions are "zero or more", it also matches null strings.

Upvotes: 1

Jan Hančič
Jan Hančič

Reputation: 53931

You don't need regular expressions for that, just use:

if ( Trim ( $str ) === '' ) echo 'empty string';

Upvotes: 20

Jared
Jared

Reputation: 8600

if (preg_match('^[\s]*$', $text)) {
    //empty
} 
else {
    //has stuff
}

but you can also do

if ( trim($text) === '' ) {
    //empty
}

Edit: updated regex to match a truly empty string - per nickf (thanks!)

Upvotes: 2

nickf
nickf

Reputation: 546025

Checking the length of the trimmed string, or comparing the trimmed string to an empty string is probably the fastest and easiest to read, but there are some cases where you can't use that (for example, when using a framework for validation which only takes a regex).

Since no one else has actually posted a working regex yet...

if (preg_match('/\S/', $text)) {
    // string has non-whitespace
}

or

if (preg_match('/^\s*$/', $text)) {
    // string is empty or has only whitespace
}

Upvotes: 9

Rob
Rob

Reputation: 8187

You don't really need a regex

if($str == '') { /* empty string */ }
elseif(trim($str) == '') { /* string of whitespace */ }
else { /* string of non-whitespace */ }

Upvotes: 0

yu_sha
yu_sha

Reputation: 4410

Expression is \A\s*+\Z

Upvotes: -1

Related Questions