Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

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!

like image 487
Tony Stark Avatar asked Dec 02 '09 16:12

Tony Stark


People also ask

Does regex match empty string?

regex matches everything for empty string ("") as a pattern #896.

Does empty regex match everything?

An empty regular expression matches everything.

How do you match an empty line in regex?

To match empty lines, use the pattern ' ^$ '.

What is the regex for white space?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.


2 Answers

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

if ( Trim ( $str ) === '' ) echo 'empty string';
like image 96
Jan Hančič Avatar answered Oct 06 '22 00:10

Jan Hančič


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
}
like image 24
nickf Avatar answered Oct 05 '22 22:10

nickf