How do I use preg_match to test for spaces?

Viewed 99495

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"

7 Answers
[\\S]

upper case- 'S' will surely work.

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.

Related