PHP笔记网

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2019-02-02 15:55:14  修改时间:2024-12-02 03:43:34  分类:11.PHP基础  编辑
<?php
$str    = "asdf{title}asdf{author}sadf{con}asfasdfasdfasf";
$mode   = "/{(.*)}/U";
$flags1 = PREG_PATTERN_ORDER; // 默认选项。整个数组是二维数组,$arr1[0]是包括边界所构成匹配字符串的数组,$arr1[1]除去边界所构成的匹配字符串的数组; 
preg_match_all($mode, $str, $arr1, $flags1);
print_r($arr1);
echo "\r\n\r\n";

$flags2 = PREG_SET_ORDER; // 整个数组是二维数组,$arr2[0][0]是第一个包括边界所构成的匹配的字符串,$arr2[0][1]是第一个除去边界所构成的匹配的字符串,之后的数组以此类推 
preg_match_all($mode, $str, $arr2, $flags2);
print_r($arr2);
echo "\r\n\r\n";

$flags3 = PREG_OFFSET_CAPTURE; // 整个数组是三维数组,$arr3[0][0][0]是第一个包括边界所构成的匹配的字符串,$arr3[0][0][1]是到达第一个匹配字符串的边界的偏移量(边界不算在内),之后以此类推,$arr2[1][0][0]是第一个包括边界所构成的匹配的字符串,$arr3[1][0][1]是到达第一个匹配字符串的边界的偏移量(边界算在内); 
preg_match_all($mode, $str, $arr3, $flags3);
print_r($arr3); 

输出:

PREG_PATTERN_ORDER:
Array
(
    [0] => Array
        (
            [0] => {title}
            [1] => {author}
            [2] => {con}
        )

    [1] => Array
        (
            [0] => title
            [1] => author
            [2] => con
        )

)


PREG_SET_ORDER:
Array
(
    [0] => Array
        (
            [0] => {title}
            [1] => title
        )

    [1] => Array
        (
            [0] => {author}
            [1] => author
        )

    [2] => Array
        (
            [0] => {con}
            [1] => con
        )

)


PREG_OFFSET_CAPTURE:
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => {title}
                    [1] => 4
                )

            [1] => Array
                (
                    [0] => {author}
                    [1] => 15
                )

            [2] => Array
                (
                    [0] => {con}
                    [1] => 27
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => title
                    [1] => 5
                )

            [1] => Array
                (
                    [0] => author
                    [1] => 16
                )

            [2] => Array
                (
                    [0] => con
                    [1] => 28
                )

        )

)

 

 

延伸阅读:

PHP 正则表达式匹配函数 preg_match 与 preg_match_all