PHP正则:正向/反向预搜索

预搜索是一个非获取匹配,不进行存储供以后使用。

1、正向预搜索  "(?=xxxxx)","(?!xxxxx)"

"(?=xxxxx)”:所在缝隙的右侧,必须能够匹配上 xxxxx 这部分的表达式,

<?php
$str = 'windows NT windows 2003 windows xp';
preg_match('/windows (?=xp)/',$str,$res);
print_r($res);

结果:

Array
(
    [0] => windows
)

这个是xp前面的windows,不会取NT和2003前面的。

格式:"(?!xxxxx)",所在缝隙的右侧,必须不能匹配 xxxxx 这部分表达式

<?php
$str = 'windows NT windows 2003 windows xp';
preg_match_all('/windows (?!xp)/',$str,$res);
print_r($res);

结果:

Array
(
    [0] => Array
        (
            [0] => windows    这个是nt前面的
            [1] => windows    这个是2003前面的
        )

)

从这里可以看出,预搜索不进行存储供以后使用。

与会存储的对比下。

<?php
$str = 'windows NT windows 2003 windows xp';
preg_match_all('/windows ([^xp])/',$str,$res);
print_r($res);

结果:

Array
(
    [0] => Array    全部模式匹配的数组    

   (
            [0] => windows N  
            [1] => windows 2
        )

    [1] => Array   子模式所匹配的字符串组成的数组,通过存储取得。
        (
            [0] => N
            [1] => 2
        )

)



2、反向预搜索  "(?<=xxxxx)","(?<!xxxxx)"

"(?<=xxxxx)" :所在缝隙的 "左侧”能够匹配xxxxx部分。

<?php
$str = '1234567890123456';
preg_match('/(?<=\d{4})\d+(?=\d{4})/',$str,$res);
print_r($res);

结果:

Array
(
    [0] => 56789012
)

匹配除了前4个数字和后4个数字之外的中间8个数字
"(?<!xxxxx)":所在缝隙的“左侧”不能匹配xxxx部分。

<?php
$str = '我1234567890123456';
preg_match('/(?<!我)\d+/',$str,$res);
print_r($res);

结果:

Array
(
    [0] => 234567890123456

)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值