如何用值检查php中的空变量?

时间:2014-12-30 21:45:12

标签: php

我有一个字符串:

$string

如果我打印它没有回复给我:

echo $string; // result in browser: blank!  in html source code:&nbsp

我尝试使用此代码来undererstand $ string为空!

if ($string!= '&nbsp' && $string!= ' ' && $string!= '' && $string!= null && $string!= '  ' && !empty($string))
echo 'true';
else
echo 'false';

但它总是让我'真实',为什么? //我认为在$ string中有很多空格或者像那样

2 个答案:

答案 0 :(得分:2)

我查了一下,这应该有效:

$strings = ['', ' ', ' ', 's', 's ', ' s'];

foreach ($strings as $string)
{
    $string = trim(str_replace(' ', ' ', $string));

    if (strlen($string) != 0)
        echo $string . ' is not empty';
    else
        echo $string . ' is empty';

    echo '<br>';
}

输出:

is empty
is empty
is empty
s is not empty
s is not empty
s is not empty

答案 1 :(得分:0)

更强大的方法可能会将此作为起点......

//correct entities
$plain=html_entity_decode($string);

if (preg_match('/[^\s]/', $plain)) {
   //string contains some non-whitespace
}