How do I use preg_match to test for spaces?

前端 未结 7 1396
Happy的楠姐
Happy的楠姐 2020-12-28 13:47

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

7条回答
  •  情深已故
    2020-12-28 14:33

    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.

提交回复
热议问题