drag2458 2017-03-09 15:47
浏览 102
已采纳

Php:正则表达式 - 如何提取匹配的多个部分并将其存储在数组中?

I have a page with the following code:-

<ul class="food">
<li>
<i>Bread and Butter</i>
</li>
<li>
<i>Cheese</i>
</li>
<li>
<i>Milk</i>
</li>
</ul>
<ul class="fruits">
<li>
<i>Apple</i>
</li>
<li>
<i>Mango</i>
</li>
<li>
<i>Strawberry</i>
</li>
</ul>

There are two unordered lists, and I want the contents which is between the italic tag, in an array per every unordered list. For example, Apple, Mango and Strawberry, which are the contents of second unordered list should be stored in one array ,say array[1], and the contents of other unordered list should be stored in array[0]. Also the number of items in any of the unordered list is variable or not known beforehand, which is another problem. The regex I tried was

<ul class=".*">\s(?:<li>\s<i>(.*)<\/i>\s<\/li>)+<\/ul>

Apart from that regex, I tried many other the whole day, but no success. I am new to regex and php and do not have much idea. Can someone help me with this? EDIT: I am allowed only to use regex to get content. Parsing is not allowed

  • 写回答

1条回答 默认 最新

  • doushang4293 2017-03-09 17:28
    关注

    Split The full String By:

    /<ul.*?>/m
    

    Then iterate over the splits and apply th following regex to capture italics value"

    /<i>(.*?)<\/i>/m
    

    Run it here

    Src:

    <?php
    
    $re = '/<ul.*?>/m';
    $re1 = '/<i>(.*?)<\/i>/m';
    $str = '<ul class="food">
    <li>
    <i>Bread and Butter</i>
    </li>
    <li>
    <i>Cheese</i>
    </li>
    <li>
    <i>Milk</i>
    </li>
    </ul>
    <ul class="fruits">
    <li>
    <i>Apple</i>
    </li>
    <li>
    <i>Mango</i>
    </li>
    <li>
    <i>Strawberry</i>
    </li>
    </ul>';
    
    $list=preg_split($re,$str);
    for($i=1;$i<count($list);$i++)
    {
        preg_match_all($re1, $list[$i], $matches);
        print_r($matches[1]);
    }
    ?>
    

    Sample Output:

    Array
    (
        [0] => Bread and Butter
        [1] => Cheese
        [2] => Milk
    )
    Array
    (
        [0] => Apple
        [1] => Mango
        [2] => Strawberry
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)