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

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

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错