How do I use preg_match to test for spaces?

kylex picture kylex · Sep 6, 2009 · Viewed 90.7k times · Source

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"

Answer

nickf picture nickf · Sep 6, 2009

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)