正则

  定界符    /

  通用原子: \d(0-9) \D \w(数字字母_) \W \s(空白符) \S

        元字符    +(1,+&)
                *(0,+&)
                ?(0,1)
                \s 单个空格,包含Tab
                \S 单个空格之外的所有字符
                \d 0-9数字
                \w 字母、数字、下划线
                \W 除\w之外的字符

  模式修正符:i不区分大小写 m将字符串通过分隔符进行分割 e s U取消贪婪模式 x A D u做utf-8中文匹配的时候使用 g全局匹配

        字位符    ^  目标字符串开头
                $  目标字符串结尾
                \b 目标字符串开头或结尾
                \B 目标字符串开头和结尾边界之间
        指定某一范围
                [A-Z][a-z][0-9]
        同时与多种模式相匹配
                100|test|hello
        否定符    ^
        子模式匹配    ()
        位数匹配    {}
        eg:
            (\s*)    连续空格
            [\s*]    空格或*
            \s{3}    3个空格
            \s[1,3] 1-3个空格
            (0-9)    '0-9'本身
            [0-9]    匹配数字
            {1-9}    写法错误
        相关函数:
    preg_match        匹配

    preg_match_all

    preg_split        分隔

    preg_replace    替换

    preg_quote        转义            

    preg_grep        条目

        

  取消贪婪模式

  .*?

  /.*/U

 

 

 

 

 

 

 

 

实例

    $a = 13717830500;
    $parrent = '/^137\d{8}$/';
    preg_match($parrent,$a,$match);
    print_r($match);

    $subject = '<b>this is title</b>';
    $parrent = '/<b>(.*)<\/b>/';
    $result = preg_replace($parrent, '\\1',$subject);
    print_r($result);

    $subject = '<b>this is title</b><b> this is title2</b>';
    $parrent = '/<b>(.*?)<\/b>/';
    $result = preg_replace($parrent, '\\1', $subject);
    print_r($result);

    $subject = 'this is 中文 ne';
    $parrent = '/[\x{4e00}-\x{9fa5}]+/u';
    preg_match($parrent,$subject,$matchs);
    print_r($matchs);

    $subject = "<img src='src/image.jpg name='test' alt='testAlt'/>'";
    $parrent = '/<img.*?name=\'(.*?)\'.*?\/>/';
    preg_match($parrent,$subject,$matchs);
    print_r($matchs);

    $subject = 'test test1 test2 test3 test4 test5,test6';
    $parrent = '/[\s,]+/';
    $result = preg_split($parrent,$subject);
    print_r($result);

    $subject = '<b>this is title</b><b>this is title2</b><b>this is title3</b>';
    $parrent = '/<b>(.*)<\/b>/U';
    preg_match_all($parrent,$subject,$matchs);
    print_r($matchs);


    $text = "April fools day is 04/01/2002\n";
    $text.= "Last christmas was 12/24/2001\n";
    function next_year($matchs){
        return ($matchs[1]).($matchs[2]+1);
    }
    $parrent = '/(\d{2}\/\d{2}\/)(\d{4})/';
    $result = preg_replace_callback($parrent,'next_year',$text);
    print_r($result);
    exit;

 

posted on 2016-12-27 16:55  爱吃柠檬不加糖  阅读(257)  评论(0)    收藏  举报

导航