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
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog