Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use preg_match to test for spaces?

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"

like image 628
kylex Avatar asked Sep 06 '09 05:09

kylex


People also ask

What is Preg_match function?

The preg_match() function returns whether a match was found in a string.

Which of the following is used by Preg_match?

Which one of the following functions are used to search a string? Explanation: The function preg_match() searches string for pattern and it returns true if pattern exists, and false otherwise. The function returns 1 if search was successful else returns 0.

What does Preg_match mean in PHP?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_split() in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array.

What does preg match return?

preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .


2 Answers

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) 
like image 162
nickf Avatar answered Sep 22 '22 21:09

nickf


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

like image 30
JYelton Avatar answered Sep 18 '22 21:09

JYelton