Share this post

Link to post

Share on other sites

Jon or Larry might give you some feedback on the regular expression. If you only want to solve the problem, you could consider using a function like strpos() instead. Something like this should work excellent:

Share this post

Link to post

Share on other sites

By pure coincidence, I just answered a very similar question on the JavaScript board, but basically, /^\S$/ does not work for 'aa' because that regex only works for a single character.

There are several variations on the regex you're using though that will work.

For starters, you can do /^\S+$/, which will confirm that all characters are non-whitespace characters, regardless of the length of the string.

Similarly, and more simply, you can use /\s/, which will search for any whitespace character in the string, meaning that if there is even one whitespace character in the string, then the regex will return the match.

Like Antonio said though, the best solution to this problem is to use the strpos function, which does not require a regex, thus it will be faster, and it's much simpler to code.

Just a small tweak to Antonio's code though: strpos returns a number on success and false on no match. As such, it's best to use the following to confirm a match:

if (strpos($str, ' ') !== false) {
// Space found.
}

As a final note, "space" and "whitespace character" have different meanings.

I assumed you meant "space" for what you want to accomplish, even though the regex metacharacter \s means "whitespace character".

Share this post

Link to post

Share on other sites

I don't understand why Larry uses this specific regex example to find spaces in a string if it can only work for a single character (and it is "space" in the example). Using stropos() makes much more sense.