zoukankan      html  css  js  c++  java
  • 正则表达式,匹配查找函数(preg_match_all)flags参数对比

    格式:

    int preg_match_all ( string pattern, string subject, array matches [, int flags] )

    参数 flags 选项有以下3个:

    PREG_PATTERN_ORDER  //是默认参数
    PREG_SET_ORDER
    PREG_OFFSET_CAPTURE

    我们用例子来看看 PREG_PATTERN_ORDER 和 PREG_SET_ORDER 的区别。(须查看源代码)

    <?php
    
    $str = '<a href="http://www.baidu.com/">百度</a>,
        <a href="http://www.google.com/">谷歌</a>,
        <a href="http://www.caiguai.net/">怪手论坛</a>';
    
    preg_match_all('/<a href="(.*?)">(.*?)</a>/', $str, $matches_pattern, PREG_PATTERN_ORDER);
    preg_match_all('/<a href="(.*?)">(.*?)</a>/', $str, $matches_set, PREG_SET_ORDER);
    
    echo "<pre>";
    
    print_r($matches_pattern);
    
    echo "<p>";
    
    print_r($matches_set);

    $matches_pattern 返回的数据为: 

    Array
    (
        [0] => Array
            (
                [0] => <a href="http://www.baidu.com/">百度</a>
                [1] => <a href="http://www.google.com/">谷歌</a>
                [2] => <a href="http://www.caiguai.net/">怪手论坛</a>
            )
    
        [1] => Array
            (
                [0] => http://www.baidu.com/
                [1] => http://www.google.com/
                [2] => http://www.caiguai.net/
            )
    
        [2] => Array
            (
                [0] => 百度
                [1] => 谷歌
                [2] => 怪手论坛
            )
    
    )

    $matches_set 返回的数据为:

    Array
    (
        [0] => Array
            (
                [0] => <a href="http://www.baidu.com/">百度</a>
                [1] => http://www.baidu.com/
                [2] => 百度
            )
    
        [1] => Array
            (
                [0] => <a href="http://www.google.com/">谷歌</a>
                [1] => http://www.google.com/
                [2] => 谷歌
            )
    
        [2] => Array
            (
                [0] => <a href="http://www.caiguai.net/">怪手论坛</a>
                [1] => http://www.caiguai.net/
                [2] => 怪手论坛
            )
    
    )

    而根据我之前阅读别人代码,就一直认为应该这么来组合结果:

    foreach ($matches_pattern[0] as $tid=>$val) {
        echo '链接:'.$matches_pattern[1][$tid];
        echo '网址:'.$matches_pattern[2][$tid];
        echo "
    ";
    }
    /**
     *  返回结果为:
     *  
    链接:http://www.baidu.com/网址:百度
    链接:http://www.google.com/网址:谷歌
    链接:http://www.caiguai.net/网址:怪手论坛 
     */

    而PREG_SET_ORDER,就在于重新组合的数据,使得数组数据可以更方便的利用:

    foreach ($matches_set as $v) {
        echo '链接:'.$v[1];
        echo '网址:'.$v[2];
        echo "
    ";
    }
    /**
     *  返回结果为:
     *  
    链接:http://www.baidu.com/网址:百度
    链接:http://www.google.com/网址:谷歌
    链接:http://www.caiguai.net/网址:怪手论坛 
     */
  • 相关阅读:
    matlab2016b和c# .net4.0混合编程
    有限元入门
    math.net 拟合
    excel 错误提示以及其他基础知识
    excel的小bug
    Servlet体系及方法
    Servlet学习笔记
    HTTP协议
    Tomcat
    反射
  • 原文地址:https://www.cnblogs.com/zhuyongzhe/p/7848491.html
Copyright © 2011-2022 走看看