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>';
and this is my code
/**
* Return HTML of select field with one option selected, built based
* on the list of options provided
* @pa开发者_JAVA技巧ram 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);
How can I get the name of the select list using a regex instead of manually writing it (extra2) ?
Try something like:
<?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
));
I guess you'll have to add some error checking here and there.
You don't. You parse the HTML using http://www.php.net/manual/en/book.dom.php.
Don't make that string to begin with. Work on the data you have, before concatenating to a string.
Most likely, you should not need to make a huge string after working on the data either. Can't you run a loop and echo the HTML out, putting in the variables were needed?
If you are sure of $option structure, you can do:
function makeSelect($name, $options) {
if (is_string($options)) {
preg_match('/<select name="(.+?)"/', $options, $match);
$name = $match[1];
...
You could also build $options to contains the nameof the select this way:
$options = array(
'name' => 'The name',
'options => ...
);
精彩评论