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 等差数列中的素数个数
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证