【问题标题】:Check variable if explode-able in PHP检查变量是否可以在 PHP 中爆炸
【发布时间】:2011-03-04 19:48:53
【问题描述】:

不确定是否有办法检查变量是否可爆炸...

我有一个城市名称数据库,有些是单字城市,有些是多字城市

例如:芝加哥、洛杉矶

当城市名称是一个单词时,我在使用“implode”时不断收到错误,所以我尝试使用“count”并使用 if 语句......没有任何运气

$citi = explode(' ', $row['city']);
$count = count($citi);
if ($count > 1) {
   $city = implode('+', $citi);
}
else {
   $city = $citi;
}

【问题讨论】:

    标签: php


    【解决方案1】:

    explode() 总是返回一个数组,无论它是否爆炸。

    $a = explode(' ', 'Chicago');
    print_r($a); 
    // output: array('Chicago')
    

    【讨论】:

      【解决方案2】:

      是的,绝对可以做到。试试stristr()

      if( stristr( $row['city'], ' ' ) )
          // It has a space, therefore explodable
      

      看起来您正在尝试将空格变成“+”。

      我只会使用str_replace()

      $city = str_replace( ' ', '+', $row['city'] );
      

      【讨论】:

      • 哈!我什至没有想过使用 str_replace 会容易得多。感谢您的回复。
      【解决方案3】:
      if(strpos($row['city'], ' ') !== false) {
        // explodable
      } else {
        // not explodable
      }
      

      【讨论】:

      • 非常感谢您的快速回答!
      【解决方案4】:

      使用explode本身看是否可以爆炸

      $a = explode(" ","Where Am I?");
      if(count($a)>1) {
           echo "explodable";
      }
      else {
           echo "No use of exploding";
      }
      

      【讨论】:

      • 非常好。它比所有其他方法都方便。
      【解决方案5】:

      这是最有效的方法。我已经实现了。

      $name = $_POST["address_name"];
      if(strpos($row['city'], ' ') !== false) {
        // explodable
        list($fname, $lname) = explode(' ', $name);
      } else {
        // not explodable
        $fname = $name;
        $lname = $name;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-11-21
        • 1970-01-01
        • 2011-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多