我有三个(可选输入的)变量:城市,州和国家.我不确定如何检查哪三个不为空,然后相应地在它们之间插入逗号.有人可能只进入一个城市,进入一个城市和州,只有一个城市和一个国家等等.我知道有一种简单的方法可以做到这一点,但我在做这件事时却遇到了麻烦,而没有使用比我需要的更多的代码行.例:
<?php
$country = $_POST['country'];
$state = $_POST['state'];
$city = $_POST['city'];
if (!empty($city)){
$location = $city;
}
if (!empty($state) && !empty($city)){
$location .= ', ' . $state;
}
if (!empty($ state) ** !empty$country)){
$location .= ', '. $country;
}
echo $location;
?>
Run Code Online (Sandbox Code Playgroud)
$location = array();
if(!empty($_POST['country'])) $location['country'] = $_POST['country'];
if(!empty($_POST['state'])) $location['state'] = $_POST['state'];
if(!empty($_POST['city'])) $location['city'] = $_POST['city'];
$location = implode(', ', $location);
Run Code Online (Sandbox Code Playgroud)
1.如果您使用它来生成数据库查询,请至少使用mysql_real_escape_string()(例如mysql_real_escape_string($_POST['country'])),除非您使用参数化查询(例如PDO或MySQLi).
2.如果要将字符串输出给用户使用htmlentities()(例如htmlentities($_POST['country'])).
$loc = array($_POST['country'], $_POST['state'], $_POST['city']);
echo implode(",", $loc);
Run Code Online (Sandbox Code Playgroud)