如果在PHP中可爆炸,请检查变量

时间:2010-06-17 07:07:39

标签: php

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

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

EX:芝加哥,洛杉矶

当城市名称是一个单词时,我使用“implode”时出现错误,所以我尝试使用“count”并使用if语句...没有运气

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

5 个答案:

答案 0 :(得分:26)

if(strpos($row['city'], ' ') !== false) {
  // explodable
} else {
  // not explodable
}

答案 1 :(得分:7)

使用爆炸自己查看它是否可以爆炸

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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

看起来你正试图将空格变成'+'。

我只想使用str_replace()

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

答案 4 :(得分:0)

这是最有效的方式。我实现了这个。

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