kylex
kylex

Reputation: 14406

How do I use preg_match to test for spaces?

How would I use the PHP function preg_match() to test a string to see if any spaces exist?

Example

"this sentence would be tested true for spaces"

"thisOneWouldTestFalse"

Upvotes: 33

Views: 106806

Answers (7)

Emma
Emma

Reputation: 27763

We can also check for spaces using this expression:

/\p{Zs}/

Test

function checkSpace($str)
{
    if (preg_match('/\p{Zs}/s', $str)) {
        return true;
    }
    return false;
}

var_dump((checkSpace('thisOneWouldTestFalse')));
var_dump(checkSpace('this sentence would be tested true for spaces'));

Output

bool(false)
bool(true)

If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.

Upvotes: 0

danielpopa
danielpopa

Reputation: 820

faster to use:

strstr($string, ' ');

Upvotes: 0

Nagy Zoltan
Nagy Zoltan

Reputation: 31

You can use:

preg_match('/[\s]+/',.....)

Upvotes: 3

rjha94
rjha94

Reputation: 4318

How about using ctype_graph for this purpose? This would expand the scope of space to mean any "white space char" that does not print anything visible on screen (like \t, \n ) also. However this is native and should be quicker than preg_match.

$x = "string\twith\tspaces" ;
if(ctype_graph($x))
    echo "\n string has no white spaces" ;
else
    echo "\n string has spaces" ;

Upvotes: 0

Avisek Chakraborty
Avisek Chakraborty

Reputation: 8309

[\\S]

upper case- 'S' will surely work.

Upvotes: 0

nickf
nickf

Reputation: 546503

If you're interested in any white space (including tabs etc), use \s

if (preg_match("/\\s/", $myString)) {
   // there are spaces
}

if you're just interested in spaces then you don't even need a regex:

if (strpos($myString, " ") !== false)

Upvotes: 55

JYelton
JYelton

Reputation: 36546

Also see this StackOverflow question that addresses this.

And, depending on if you want to detect tabs and other types of white space, you may want to look at the perl regular expression syntax for things such as \b \w and [:SPACE:]

Upvotes: 4

Related Questions