【问题标题】:Preg_split, how to keep delimiter?preg_split,如何保留分隔符?
【发布时间】:2015-03-02 09:11:35
【问题描述】:

我试图保留 preg_split 分隔符( 和 )而不将其分隔在新的数组位置并且无法弄清楚。因此,我们将不胜感激。

我正在尝试从下一个 html 代码中取出每一行并将其放在不同的数组位置:

<tr><td> one column </td><td>second column</td></tr><tr><td> one column </td><td>second column</td></tr>

这是我得到的:

array_unique(preg_split('[<tr[^>]*>(.*?)</tr>]',$table,NULL,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));

如果我对数组执行 var_dump,此代码将显示:

array(2) {
    [0]=>
    string(43) "<td> one column </td><td>second column</td>"
    [1]=>
    string(43) "<td> one column </td><td>second column</td>"
  }

而我想要的是:

array(2) {
    [0]=>
    string(52) "<tr><td> one column </td><td>second column</td></tr>"
    [1]=>
    string(52) "<tr><td> one column </td><td>second column</td></tr>"
  }

在此之前,非常感谢您的帮助和时间。

【问题讨论】:

    标签: php html regex delimiter preg-split


    【解决方案1】:

    只需捕获&lt;tr&gt; 标记。由于您使用的是PREG_SPLIT_DELIM_CAPTURE 参数,因此这也会返回正在捕获的字符。

    array_unique(preg_split('[(<tr[^>]*>.*?</tr>)]',$table,NULL,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
    

    示例 1:

    $st = '<tr><td> one column </td><td>second column</td></tr><tr><td> one column </td><td>second column</td></tr>';
    $match = preg_split('[(<tr[^>]*>.*?</tr>)]',$st,NULL,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    print_r($match);
    

    输出:

    Array
    (
        [0] => <tr><td> one column </td><td>second column</td></tr>
        [1] => <tr><td> one column </td><td>second column</td></tr>
    )
    

    示例 2:

    $st = '<tr><td> one column </td><td>second column</td></tr><tr><td> one column </td><td>second column</td></tr>';
    $match = array_unique(preg_split('[(<tr[^>]*>.*?</tr>)]',$st,NULL,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
    print_r($match);
    

    输出:

    Array
    (
        [0] => <tr><td> one column </td><td>second column</td></tr>
    )
    

    【讨论】:

    • 这太棒了,就像一个魅力。你个摇滚人!!非常感谢!
    【解决方案2】:

    不要为此使用 preg_split。你想使用 preg_match_all:

    preg_match_all('[<tr[^>]*>.*?</tr>]', $table, $matches, PREG_PATTERN_ORDER);
    $rows = $matches[0];
    

    不过有几个问题:为什么要使用 array_unique?为什么要使用正则表达式解析 HTML?改用 xpath 之类的东西。

    【讨论】:

    • 感谢您的评论。您的解决方案也有效!我正在使用 array_unique 因为我正在过滤数组结果以不存储重复的行。我正在使用 PHPexcel 中的表构建数组数据并删除重复的行。
    猜你喜欢
    • 2018-04-27
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多