对我现有代码的简单正则表达式添加


Simple regex addition to my existing code

$options = '<select name="extra2"  id="extra2" class="select_smaller">
    <option value="Algema">Algema</option>
    <option value="Barkas">Barkas</option>
.
.
.
</select>';

这是我的代码

/**
 * Return HTML of select field with one option selected, built based
 * on the list of options provided
 * @param mixed $options array of options or HTML of select form field
 * @return string HTML of the select field
 */
function makeSelect($name, $options) {
if (is_string($options)) {
    // assuming the options string given is HTML of select field
    $regex = '/<option value='"([a-zA-Z0-9]*)'"'>/';
    $count = preg_match_all($regex, $options, $matches);
    if ($count) {
        $options = $matches[1];
    } else {
        $options = array();
    }
}
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));
}
echo makeSelect('extra2', $options);

如何使用正则表达式而不是手动编写它(extra2)来获取选择列表的名称?

尝试类似操作:

<?php
function selectOption($htmlSelect, array $data = array()) {
    $result = $htmlSelect;
    $dom = new DOMDocument();
    if ($dom->loadXml($htmlSelect)) {
        $selectName = $dom->documentElement->getAttribute('name');
        if (isset($data[$selectName])) {
            $xpath = new DOMXPath($dom);
            $optionNodeList = $xpath->query('//option[@value="' . $data[$selectName] . '"]');
            if ($optionNodeList->length == 1) {
                $optionNodeList->item(0)->setAttribute('selected', 'selected');
                $result = $dom->saveXml($dom->documentElement, LIBXML_NOEMPTYTAG);
            }
        }
    }
    return $result;
}
$htmlSelect = '<select name="extra2" id="extra2" class="select_smaller">
    <option value="Algema">Algema</option>
    <option value="Barkas">Barkas</option>
</select>';
echo selectOption(
    $htmlSelect,
    array('extra2' => 'Barkas') // could be $_GET, $_POST or something else
));

我想你必须在这里和那里添加一些错误检查。

你没有。您可以使用 http://www.php.net/manual/en/book.dom.php 解析 HTML。

不要一开始就制作该字符串。在连接到字符串之前处理您拥有的数据。

最有可能的是,在处理数据后,您也不需要制作一个巨大的字符串。你不能运行一个循环并回显 HTML 出来,需要输入变量吗?

如果你确定$option结构,你可以做:

function makeSelect($name, $options) {
    if (is_string($options)) {
        preg_match('/<select name="(.+?)"/', $options, $match);
        $name = $match[1];
        ...

您还可以通过以下方式构建包含选择名称的$options:

$options = array(
    'name'   => 'The name',
    'options => ...
);