$options = '<select name="extra2" id="extra2" class="select_smaller">
<option value="Algema">Algema</option>
<option value="Barkas">Barkas</option>
.
.
.
</select>';
,這是我的代碼簡單的regex我除了現有的代碼
/**
* 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)的名字?
你可以是一個小更清楚你試圖完成什麼?在我看來,你想要使用正則表達式來解析一段HTML,以捕獲選擇輸入中可用選項的名稱?爲什麼在PHP中有一個HTML字符串呢?你從HTML獲取? – 2011-05-16 13:59:59
我有500個表格,每個表格有2-3個下拉列表。我無法一一編輯它們,因此這段代碼將幫助我生成並顯示正確的結果,以便根據url數據選擇選項值。該代碼工作正常,除了我需要手動添加名稱在他們每個人的事實。當我有解決方案時,我會用大量搜索和替換程序來替換所有表單。 – EnexoOnoma 2011-05-16 14:09:18
讓我重新解釋一下這個問題。 $ options變量的內容來自哪裏?你是自己製作弦還是從別的地方得到它? – 2011-05-16 14:19:29