Want to check white spaces in a form. If somebody inserted some text without spaces, what to开发者_开发知识库 do? How validate this
\s
will match whitespace in a regular expression (and both PHP and JavaScript support regex).
If you just want to trim excess whitespace from either the left side or the right side you could use trim(), ltrim() and rtrim(). If you want to remove all space you could use a regexp removing all spaces:
$foo = preg_replace( '/\s+/', '', $foo );
EDIT:
So if you want to test whether there are white spaces in the text you can still use the above regular expression just with the preg_match function instead. This will give you all the matching results. So what I would do is to check whether the resulting array is empty or not.
So:
$subject = "bingabongflingflong";
$pattern = '/\s+/';
if (preg_match($pattern, $subject)) {
echo "A white space was found";
} else {
echo "No white space was found";
}
This will result in saying No white space was found, if you add a white space it will return A white space was found. You can also do it this way to get all the matches and look at the resulting array:
$subject = "binga bongfling flong";
$pattern = '/\s+/';
preg_match($pattern, $subject, $matches);
print_r($matches);
This will print something like:
Array
(
[0] =>
)
精彩评论