正在寻找一种方法来自动获取选择框的名称或id,并使用它从url中选择适当的选项.代码


Searching for a way to automatically get the name or id of a select box and use it to select the appropriate option from the url. Code given

我有以下下拉列表,并根据url选择选项,例如www.domain.com/?car=Algema&city=Paris

问题是我有104个不同的表单,其中一些包含多个下拉列表。它们不可能被取代。是否有办法将$_GET['car']替换为$_GET['get the name of select id or name automatically'] ?

也许重写正则表达式脚本,将取代我所有的php文件?

<select name="car" id="car" class="select">
<option value="Algema" <?php echo $_REQUEST['car'] == 'Algema' ? 'selected="selected"' : '';?>>Algema</option>
<option value="Barkas" <?php echo $_REQUEST['car'] == 'Barkas' ? 'selected="selected"' : '';?>>Barkas</option>
<option value="Cadillac" <?php echo $_REQUEST['car'] == 'Cadillac' ? 'selected="selected"' : '';?>>Cadillac</option>
</select>

使用一些不那么重复的语句:

function makeSelect($name, $options) {
    foreach ($options as &$option) {
        $selected = isset($_GET[$name]) && $_GET[$name] == $option;
        $option = sprintf('<option value="%1$s"%2$s>%1$s</option>',
                          htmlspecialchars($option),
                          $selected ? ' selected="selected"' : null);
    }
    return sprintf('<select name="%1$s" id="%1$s" class="select">%2$s</select>',
                   htmlspecialchars($name),
                   join($options));
}
$options = array('Algema', 'Barkas', 'Cadillac', …);
echo makeSelect('car', $options);

您可能可以使用Regex自动将选项名称提取为数组格式,但您仍然至少需要手动确认所有内容。