Reputation: 14406
How would I use the PHP function preg_match() to test a string to see if any spaces exist?
"this sentence would be tested true for spaces"
"thisOneWouldTestFalse"
Upvotes: 33
Views: 106806
Reputation: 27763
We can also check for spaces using this expression:
/\p{Zs}/
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'));
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
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
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
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