How to use preg_match to test for spaces?


Question

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"

1
26
9/6/2009 5:45:47 AM

Accepted Answer

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)
48
8/17/2010 4:40:28 AM

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:]


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon