【问题标题】:How to tell if a string is empty other than <br /> tags?如何判断字符串是否为空而不是 <br /> 标签?
【发布时间】:2012-03-03 14:09:19
【问题描述】:

我有三个变量,可能包含也可能不包含数据。

我们称它们为 $name、$address 和 $telephone。

假设我想将它们全部合并到一个变量 $contact 中,每个变量都在单独的一行中。

$contact = $name.'&lt;br /&gt;'.$address.'&lt;br /&gt;'.$telephone;

$contact 然后被放入一个数组中。该数组最终通过一个 foreach 循环,不处理任何等于'' 的变量。除了两个&lt;br /&gt; 标签之外,我如何判断字符串是否为空?我尝试将 $contact 复制到 $test_contact 并运行 str_replace('&lt;br /&gt;', '', $test_contact; 但即使所有变量都设置为 '' $test_contact == '' 仍然评估为假。在str_replace() 之后,我也尝试过trim(),但这也不起作用。我也尝试过使用===,但同样没有运气。

我错过了什么?有没有更好的方法来做到这一点?

标记

【问题讨论】:

    标签: php string null


    【解决方案1】:

    str_replace 路线肯定行得通:

    if(trim(str_replace('<br />', '', $test_contact)) == '') {
      echo 'empty';
    }
    

    但是你为什么不在将它插入你的数组之前检查一下呢?

    if(strlen($name) + strlen($address) + strlen($telephone) == 0) {
      // don't insert
    }
    

    【讨论】:

      【解决方案2】:
      if(strlen(str_replace("<br />", "", $test_contact)) === 0) {
        //empty
      }
      

      【讨论】:

        【解决方案3】:

        插入前检查:

        if ($name.$address.$telephone == '')

        然后是空的

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-21
          • 1970-01-01
          • 1970-01-01
          • 2019-03-02
          • 2010-11-21
          • 1970-01-01
          • 2011-05-31
          • 2020-08-26
          相关资源
          最近更新 更多