PHP使用preg_match_all无法提取网页第二个select下拉框option选项问题
问题原因
你当前写的正则没有限定<option>所属的下拉框范围,会全局匹配页面所有下拉的选项,自然无法单独提取数量选择框的内容。亚马逊的库存数量选择下拉框有固定的id="quantity"特征,针对这个特征筛选即可。
推荐解决方案(DOM解析,稳定性更高)
正则匹配HTML容错率极低,页面结构稍有变动就会失效,优先用PHP内置的DOM解析工具处理:
$html = file_get_contents("https://www.amazon.co.jp/-/en/dp/B09C1PM7K3?th=1"); // 屏蔽HTML不规范导致的解析警告 libxml_use_internal_errors(true); $dom = new DOMDocument(); $dom->loadHTML($html); libxml_clear_errors(); $xpath = new DOMXPath($dom); // 直接定位id为quantity的数量选择框下的所有option $optionNodes = $xpath->query('//select[@id="quantity"]/option'); $quantityOptions = []; foreach ($optionNodes as $node) { $quantityOptions[$node->getAttribute('value')] = trim($node->nodeValue); } // 打印所有数量选项 print_r($quantityOptions); // 获取最大可选数量 $finalQty = end($quantityOptions); dd($finalQty);
正则兼容方案(不推荐,仅作参考)
如果一定要用正则实现,需要先匹配到数量选择框的完整代码块,再在块内匹配option:
$html = file_get_contents("https://www.amazon.co.jp/-/en/dp/B09C1PM7K3?th=1"); // 先匹配id为quantity的select完整内容 preg_match('@<select[^>]+id="quantity"[^>]*>(.*?)</select>@s', $html, $selectBlock); if (isset($selectBlock[1])) { preg_match_all('@<option value="([^"]+)">([^<]+)</option>@', $selectBlock[1], $matches); $quantityOptions = []; foreach ($matches[1] as $index => $value) { $quantityOptions[$value] = trim($matches[2][$index]); } print_r($quantityOptions); $finalQty = end($quantityOptions); dd($finalQty); }
内容的提问来源于stack exchange,提问作者Hassaan
相关产品推荐
相关产品推荐

