首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP中的正则表达式模式\K备选方案

PHP中的正则表达式模式\K备选方案
EN

Stack Overflow用户
提问于 2012-09-15 12:34:46
回答 2查看 837关注 0票数 1

我一直在使用\K,但最近我意识到它不能在低于5.2.4版本的PHP中工作。所以我在寻找一种不同的方式。

代码语言:javascript
运行
复制
<?php
    $html = '<div>hello</div>
        <div class="someclass">hi</div>
        <div class="sample">this text should be included</div>
        <div>bye</div>
    ';
    // $pattern = '/<div.+class=["\']sample["\'].+div>\K/i'; // <-- this doesn't work below v5.2.4
    $pattern = '/(?<=<div.+class=["\']sample["\'].+div>)/i'; // causes an error.
    $array = preg_split($pattern, $html);
    print_r($array);
?>

我已经看到可以使用(?<=)作为替代方案,我尝试了一下,但它导致了错误。有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-15 13:42:27

好吧,我找到了一个变通办法。preg_split()接受第四个参数中的PREG_SPLIT_DELIM_CAPTURE标志,因此匹配的字符串可以包含在数组的分隔元素中。我只需要选择一个额外的元素来提取字符串,这不是那么多的工作要做。

代码语言:javascript
运行
复制
<?php
    $html = '<div>hello</div>
        <div class="someclass">hi</div>
        <div class="sample">this text should be included</div>
        <div>bye</div>
    ';
    $pattern = '/(<div.+class=["\']sample["\'].+div>)\${0}/i'; 
    $array = preg_split($pattern, $html, null, PREG_SPLIT_DELIM_CAPTURE);
    print_r($array);
?>
票数 0
EN

Stack Overflow用户

发布于 2012-09-15 13:43:15

我会重新实现split。在Perl中,它看起来如下所示:

代码语言:javascript
运行
复制
my @matches;
while (/\G((?s:.*?)...)/gc) {
   push @matches, $1;
}

push @matches, /\G(.+)\z/sg;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12434528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档