• php 正则表达式一.函数解析


    php正则表达式官方手册参考。。。。。。。

    一.php中 常用的正则表达式函数

      1.preg_match与preg_match_all

        preg_match: 函数信息

        preg_match_all:函数信息

        preg_match与preg_match_all区别:

          preg_match的只要匹配成功就结束匹配,返回值是0或者1,如果有$matchs那么返回匹配成功的结果

          preg_match_all:返回匹配的次数,如果有$matchs那么返回所有匹配成功的结果

    $pattren = '/[0-9]/';
    $subject = 'alfjsakldfnjf12f12ggd4j它';
    
    $res1 = preg_match($pattren,$subject,$match);
    echo '$res1='.$res1;
    echo "<br />";
    print_r($match);
    echo "<hr />";
    $res2 = preg_match_all($pattren,$subject,$match2);
    echo '$res2='.$res2;
    echo "<br />";
    print_r($match2);
    echo "<hr />";

      输出:

        $res1=1
        Array ( [0] => 1 )


        $res2=5
        Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 4 ) )

      2.preg_replace与preg_filter

        preg_replace:函数信息

        preg_filter:函数信息

        区别:当$subject是数组时,preg_replace,返回所有的元素,而preg_filter只返回数组中匹配的值

        

    $pattren = '/[0-9]/';
    $replace = '女神';
    //$subject = 'alfjsakldfnjf12f12ggd4j它';
    $subject = array('al1fjs','akldf','njf12f','12ggd4j它');
    
    $str1 = preg_replace($pattren,$replace,$subject);
    $str2 = preg_filter($pattren,$replace,$subject);
    
    print_r($str1);
    echo "<br />";
    echo "<hr />";
    print_r($str2);

      //输出

        Array ( [0] => al女神fjs [1] => akldf [2] => njf女神女神f [3] => 女神女神ggd女神j它 ) 


        Array ( [0] => al女神fjs [2] => njf女神女神f [3] => 女神女神ggd女神j它 )

      3.preg_grep.返回数组中与$pattern匹配的数组元素,并不替换

    $pattern = '/[0-9]/';
    $subject = array('fal','jsd24j','f1','2j40','9gaaf');
    
    $arr = preg_grep($pattern, $subject);
    
    print_r($arr);

      输出:Array ( [1] => jsd24j [2] => f1 [3] => 2j40 [4] => 9gaaf )

      4.preg_split :通过正则表达式分割字符串

    $pattern = '/[0-9]/';
    $subject = '妹1子45啊,约234不2380约啊?';
    
    $arr = preg_split($pattern,$subject);
    print_r($arr);

      输出:

        Array ( [0] => 妹 [1] => 子 [2] => [3] => 啊,约 [4] => [5] => [6] => 不 [7] => [8] => [9] => [10] => 约啊? )

      5.preg_quote:转义正则表达式字符

    $str = 'reas{12}[23]_+fahiu~=';
    
    $res = preg_quote($str);
    
    print_r($res);

      输出:reas{12}[23]_+fahiu~=

  • 相关阅读:
    第一学期心得
    第十三次作业
    第十二次作业
    第十一次作业
    第十次作业
    第九次作业
    第八次作业
    第七次作业
    第六次作业
    第五次作业
  • 原文地址:https://www.cnblogs.com/tumio/p/4850497.html
Copyright © 2020-2023  润新知