根据提交的位置,在城市、州、国家输入之间插入逗号


Inserting commas between city, state, country input depending on which locations are submitted

我有三个(可选输入的)post变量:城市、州和国家。我不确定如何检查哪三个不是空的,然后在它们之间相应地插入逗号。有人可能只进入一个城市,进入一个城市和一个州,只进入一个城市和一个国家,等等。我知道有一种简单的方法可以做到这一点,但是如果没有比我需要的更多的代码行,我就很难做到这一点。例子:

<?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;
?>
$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);

安全预防措施

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);