• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

php正则表达式

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
// 用preg_match 模仿实现 preg_match_all
function custom_preg_match_all($pattern, $subject)
{
    $offset = 0;
    $match_count = 0;
    while(preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, $offset))
    {
        // Increment counter
        $match_count++;
    
        // Get byte offset and byte length (assuming single byte encoded)
        $match_start = $matches[0][1];
        $match_length = strlen($matches[0][0]);

        // (Optional) Transform $matches to the format it is usually set as (without PREG_OFFSET_CAPTURE set)
        foreach($matches as $k => $match) $newmatches[$k] = $match[0];
        $matches = $newmatches;
    
        // Your code here
        echo "Match number $match_count, at byte offset $match_start, $match_length bytes long: ".$matches[0]."\r\n";
            
        // Update offset to the end of the match
        $offset = $match_start + $match_length;
    }

    return $match_count;
}

 正则匹配练习:

文本源: <div>2</div> 2<div>1</div>abcd

模式1:
<div>.*</div>
匹配结果:
<div>2</div> 2<div>1</div>

模式2
<div>.*?</div>
匹配结果:
<div>2</div>
<div>1</div>

对于模式2,如果文本源变为:
<div><div>2</div> 2<div>1</div>abcd
匹配结果:
Match 1: <div><div>2</div> 1 17
Match 2: <div>1</div> 20 12
显然有问题;
解决办法:
模式3:
<div>((?!</?div>).)*</div>
匹配结果:
Match 1: <div>2</div> 5 12
Group 1: 2 10 1
Match 2: <div>1</div> 19 12
Group 1: 1 24 1

    


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
隐藏index.php发布时间:2022-07-10
下一篇:
用PHP导出MySQL数据库内容为.sql文件发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap