douhuan1979 2012-09-15 04:34 采纳率: 100%
浏览 74
已采纳

PHP中的正则表达式模式\ K替代品

I've been using \K quite a lot but recently realized that it does not work in PHP below v5.2.4. So I'm looking for a different way.

<?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);
?>

I've seen somewhere (?<=) can be used as the alternative and I tried it but it causes an error. Any suggestion?

  • 写回答

2条回答 默认 最新

  • douan1893 2012-09-15 05:42
    关注

    Okay, found a workaround. preg_split() accepts the PREG_SPLIT_DELIM_CAPTURE flag in the fourth parameter so the matching string can be included in the delimited elements of array. I just need to pick one additional element to extract the strings and it is not that much work to do.

    <?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);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计