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

来源:phpservice 发布时间:2019-03-28 14:53:42 阅读量:1170

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

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

)

标签: PHP 环境搭建
分享:
评论:
你还没有登录,请先