How do I find out if a string contains ONLY whitespaces and nothing else? The number of such spaces does not matter.
if () // $string contains ONLY whitespaces and nothing else
{
// do something
}
Best if can provide a solution that can be generalised to any character: How do I find if a string contains ONLY some character and nothing else
You can use regular expressions:
if (preg_match('/^\s*$/', $string)) {
// do something
}
This expression verifies that the string contains only white-space characters or nothing at all. To exclude empty strings as well, use /^\s+$/
.
Try like this:
if ( preg_match('/\s/',$mystring) )
A non-regex approach could be:
if(strlen($string) >= 1 && empty(trim($string))) {
empty(trim($string))
removes all whitespace then checks if the string is empty. strlen($string) >= 1
confirms the string wasn't empty to start with. If empty strings are also allowed that check can be removed.
The shortest approach:
$s && !trim($s)
$s
will be evaluated to True
only if it's not empty(contains anything)Testing:
$s = " \t
";
var_dump($s && !trim($s)); // true
$s = "";
var_dump($s && !trim($s)); // false
Useful info about whitespaces:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"
" (ASCII 10 (0x0A)), a new line (line feed).
"" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
There are two ways of achieving this: fast&dirty, and true; Fast wast way is run every char in $string and check it:
$is_space=true;
for($i = 0; $i<strlen($string); $i++){
if($string[$i]!==' '){
$is_space=false;
}
}
so, here if $is_space is true - then your string contains spaces only;
The second way is regexp, you need to dive a bit deeper http://php.net/manual/ru/function.preg-match.php, and you need regexp like that
\S+
if you can't find smth that is not whitespace - than you have in this string whitespaces only.
Of couse you need to check the string length, and there are many ways to check what you need using regexp.
You can use regex for checking if a string contains only white spaces.
if(preg_match('~\s*~', $string) ) {
//do something...
}
If you want to check for individual white spaces, then use corresponding escape sequences:
if(preg_match('~[
]*~', $string) ) {
//do something...
}