6.2. 子表达的嵌套

未匹配的标注

子表达式允许嵌套,并且可以多重嵌套

拿我们上面匹配的那个ip地址举例子,我们刚才写的表达式是

/(\d{1,3}\.){3}\d{1,3}/

这样是不够严谨的,因为IP地址最大的是255,刚才我们明显没有加限制,所以现在我们使用子表达式嵌套的方式来重新写一下

<?php

//字符串
$str = '192.168.0.1 255.255.255.0 8.8.8.8';

//正则表达式
$regular = '/(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2}))\.){3}((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2}))/';

//执行匹配正则表达式
preg_match_all($regular, $str, $matches);

//打印结果
echo '<pre>';
print_r($matches);
echo '</pre>';

输出结果

Array
(
    [0] => Array
        (
            [0] => 192.168.0.1
            [1] => 255.255.255.0
            [2] => 8.8.8.8
        )

    [1] => Array
        (
            [0] => 0.
            [1] => 255.
            [2] => 8.
        )

    [2] => Array
        (
            [0] => 0
            [1] => 255
            [2] => 8
        )

    [3] => Array
        (
            [0] => 
            [1] => 255
            [2] => 
        )

    [4] => Array
        (
            [0] => 
            [1] => 
            [2] => 
        )

    [5] => Array
        (
            [0] => 168
            [1] => 
            [2] => 
        )

    [6] => Array
        (
            [0] => 0
            [1] => 
            [2] => 8
        )

    [7] => Array
        (
            [0] => 1
            [1] => 0
            [2] => 8
        )

    [8] => Array
        (
            [0] => 
            [1] => 
            [2] => 
        )

    [9] => Array
        (
            [0] => 
            [1] => 
            [2] => 
        )

    [10] => Array
        (
            [0] => 
            [1] => 
            [2] => 
        )

    [11] => Array
        (
            [0] => 1
            [1] => 0
            [2] => 8
        )

)

求职:

最近在考虑跳槽,有没有企业招人或者内推一下的,请加我 QQ:15593838 详谈。

北京、上海、广州、深圳、杭州、江苏等地区优先考虑

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~