How would I use the PHP function preg_match() to test a string to see if any spaces exist?
"this sentence would be tested true for spaces"
"thisOneWouldTestFalse"
The preg_match() function returns whether a match was found in a string.
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.
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.
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 .
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)
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:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With