views:

1705

answers:

3

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

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)
nickf
You've got the strpos parameters around the wrong way. Should be: if (strpos($myString, " ") !== false)
ncatnow
@ncatnow, thanks for the heads up. That's been sitting there, wrong, for almost a year. :p
nickf
+2  A: 

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

JYelton
`\b` probably wouldn't help, since it will match the start and end of the string: eg `preg_match("/\\b/", "abc")` == true
nickf
Good point, I was just thinking "word boundaries" and not remembering it would match on the ends.
JYelton
A: 

preg_match('/[\s]+/',.....)

Nagy Zoltan