duanhao9176 2014-07-18 18:54
浏览 61
已采纳

preg_match_all从select选项中检索数据

<select name="address_town" id="address_town" class="locationTown">
 <option value="#ANY">Empty</option>
 <option value="438" >First</option>
 <option value="420" >Second</option>
</select>

I want to retrieve data which are #ANY-Empty, 438-First and 420-Second I wrote a code but i could retrieve only first data. I want to all of them. My code is below:

preg_match_all('/<select[^>]+?address_town[^>]+?>(.*?)<\/select>/', $open, $matches);
$options = $matches[1];
foreach ($options as $select) {
    preg_match_all('/<option value="(.*?)">(.*?)<\/option>/', $select, $matches2);
}   
print_r($matches2);

Thanks for helping..

  • 写回答

1条回答 默认 最新

  • douchiwan1503 2014-07-18 19:38
    关注

    Firstly, at least in your example, the first preg_match_all is useless. Then to obtain the data you are asking simply do this :

    preg_match_all('/<option value="(.*?)"\s*>(.*?)<\/option>/', $html, $matches, PREG_SET_ORDER);
    foreach ($matches as $val) {
        echo $val[1].'-'.$val[2];
    }
    

    note that I added "\s*" after the value="" because you had spaces after it on some rows.

    You may want to refer to the manual examples for more information http://php.net/manual/en/function.preg-match-all.php

    EDIT: I didn't try running the code but this is the spirit :

    preg_match_all('/<select[^>]+?address_town[^>]+?>(.*?)<\/select>/s', $open, $matches);
    $options = $matches[1];
    foreach ($options as $select) {
        preg_match_all('/<option value="(.*?)"\s*>(.*?)<\/option>/', $select, $matches, PREG_SET_ORDER);
        foreach ($matches as $val) {
            echo $val[1].'-'.$val[2].'
    ';
        }
    }   
    

    I added the s modifier at the end of the regexp so that the .* will accept the newline characters

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题