像这样的东西怎么样:
$html = <<<HTML
<option value="TTO">1031</option><option value="187">187</option>
<option value="TWO">2SK8</option><option value="411">411</option>
<option value="AEL">Abec 11</option><option value="ABE">Abec11</option>
<option value="ACE">Ace</option><option value="ADD">Addikt</option>
<option value="AFF">Affiliate</option><option value="ALI">Alien Workshop</option>
<option value="ALG">Alligator</option><option value="ALM">Almost</option>
HTML;
$matches = array();
if (preg_match_all('#<option\s+value="([^"]+)">([^<]+)</option>#', $html, $matches)) {
$list = array();
$num_matches = count($matches[0]);
for ($i=0 ; $i<$num_matches ; $i++) {
$list[$matches[1][$i]] = $matches[2][$i];
}
var_dump($list);
}
输出 ( $list) 将是:
array
'TTO' => string '1031' (length=4)
187 => string '187' (length=3)
'TWO' => string '2SK8' (length=4)
411 => string '411' (length=3)
'AEL' => string 'Abec 11' (length=7)
'ABE' => string 'Abec11' (length=6)
'ACE' => string 'Ace' (length=3)
'ADD' => string 'Addikt' (length=6)
'AFF' => string 'Affiliate' (length=9)
'ALI' => string 'Alien Workshop' (length=14)
'ALG' => string 'Alligator' (length=9)
'ALM' => string 'Almost' (length=6)
一些解释:
- 我用
preg_match_all尽可能多地匹配
([^"]+)意思是“所有不是双引号的东西(因为它会标记 的结尾value),至少一次,并且尽可能多的 ( +)
([^<]+)意思差不多,但用<而不是"作为结束标记
preg_match_all会给我一个数组,其中包含$matches[1]与第一组匹配的所有内容的列表(),以及$matches[2]与第二组匹配的内容()
- 所以我需要遍历结果以重新构建让您感兴趣的列表:-)
希望这会有所帮助 - 并且您了解它的作用和方式,以便下次您可以帮助自己;-)
作为旁注:使用正则表达式来“解析”HTML 通常不是一个好主意......如果你有一个完整的 HTML 页面,你可能想看看DOMDocument::loadHTML.
如果你不这样做并且选项的格式没有明确定义......好吧,作为预防措施,向正则表达式添加一些东西可能会证明是有用的...... (就像在这里和那里接受空格,接受其他属性, ...)