• php使用正则函数使用详解


    1. int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

    <?php
    $title = "Replacement Canon BP-511 Camcorder Battery [Item ID:3-236-523]";
    if( preg_match("/([Item ID:)([0-9]+)-([0-9]+)-([0-9]+)(])/i",$title,$arr) ){
        echo "<pre>";
        print_r($arr);
        echo "</pre>";
    }
    ?>
    //返回结果是
    Array
    (
        [0] => [Item ID:3-236-523]
        [1] => [Item ID:
        [2] => 3
        [3] => 236
        [4] => 523
        [5] => ]
    )
    <?php
      // 下面的例子演示了将文本中所有 <pre></pre> 标签内的关键字(php)显示为红色。 
        $str = "<pre>学习php是一件快乐的事。</pre><pre>所有的phper需要共同努力!</pre>";
        $kw = "php";
        preg_match_all('/<pre>([sS]*?)</pre>/', $str, $mat);
        $length = count($mat[0]);
        for ($i=0; $i<$length; $i++) {
            $mat[0][$i] = $mat[1][$i];
            $mat[0][$i] = str_replace($kw, '<span style="color:#ff0000">' . $kw . '</span>', $mat[0][$i]);
            $str = str_replace($mat[1][$i], $mat[0][$i], $str);
       }
       echo $str;
    ?>

    特点:返回0或1 ,仅对$subject 匹配一次,若符合 $pattern则返回1,否则返回0;

              $matches:数组类型,$matches[0]:匹配到的全部字符,$matches[1]...:此内容是其字表达式内匹配到的字符串( );

    preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match.

    //实例
    <?php
    // 从 URL 中取得主机名
    
    preg_match("/^(http://)?([^/]+)/i",
        "http://www.php.net/index.html", $matches);
    $host = $matches[2];
    
    echo $host;
    // 从主机名中取得后面两段
    
    preg_match("/[^./]+.[^./]+$/", $host, $matches);
    echo "domain name is: {$matches[0]}
    ";
    // 本例执行后将输出: domain name is: php.net
    
    ?>

    2.  int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

         Return Values  :Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

    <?php
    preg_match_all ("|<[^>]+>(.*)</[^>]+>|U",
        "<b>example: </b><div align=left>this is a test</div>",$out, PREG_PATTERN_ORDER); // 注意PREG_PATTERN_ORDER和PREG_SET_ORDER的区别
    
    print $out[0][0].", ".$out[0][1]."
    ";
    print $out[1][0].", ".$out[1][1]."
    ";
    echo "<pre>";
    print_r($out);
    ?>
    //返回的结果
    <b>example: </b>, <div align=left>this is a test</div>
    example: , this is a test
    <pre>Array
    (
        [0] => Array
            (
                [0] => <b>example: </b>                     //第一次匹配到的内容
                [1] => <div align=left>this is a test</div> //第二次匹配到的内容
            )
    
        [1] => Array
            (
                [0] => example:      //第一次匹配到的值表达式的内容"(.*)"
    [
    1] => this is a test//第二次匹配到的值表达式的内容"(.*)"
    ) )

      与preg_match区别是:全部匹配 $subject,直到没有符合规则($pattern)为止。

       注意PREG_PATTERN_ORDER和PREG_SET_ORDER的区别:

       PREG_PATTERN_ORDER:将匹配的全部内容放在$match[0][] ; 将子表达式的内容放在 $match[1][];按序放置。

       PREG_SET_ORDER  :将匹配到的内容和子表达式的内容放在同一维数组中 $match[][].

    3.  preg_replace :按规则 搜索并替换。注意后向引用。

    $subject = 'this hs 7 words and 31 letters';
    $result = preg_replace(array('/d+/','/[a-z]+/'), array('num<>','word<>'), $subject);
    $result2 = preg_replace(array('/[a-z]+/','/d+/'), array('word<>','num<>'), $subject);
    
    var_dump($result2);
    
    $string = "Is is the cost Of of gasoline going up up";
    $pattern = "/([a-z]+) \1/i";                         //这里的\1不能使用$1或$1
    $str = preg_replace($pattern, "\1", $string);            //这里的\1可以使用$1或$1,引用第一个子匹配
    //echo $str;            //效果是Is the cost of gasoline going up
    
    
    //数组形式每个pattern使用replacement中对应的 元素进行替换. 如果replacement中的元素比pattern中的少, 多出来的pattern使用空字符串进行替换. 
    $patterns = array('/(19|20d{2})-(d{1,2})-(d{1,2})/', '/^s*{(w+)}s*=/');
    $replace = array('\1/\2/\3', '$\1 =');
    print preg_replace($patterns, $replace, '{startDate} = 2010-6-19');//效果是$startDate = 2010/20/6
    
    /*
     "\1/\3/\4"
    \1表示第一个匹配项年份即((19|20)d{2})模式 结果为2010
    \3表示第三个匹配项月份即(d{1,2})模式 结果为6
    \4表示第四个匹配项日即第二个(d{1,2})模式 结果为19
    
    */
    
    
    
    $string = "April 15, 2003";
    $pattern = "/(w+) (d+), (d+)/i";
    //$replacement = "${1},$3";    //第一种用法 美元符号${1}  可以匹配后面跟数字的形式,${1}2525;
    //$replacement = "\1,\3";      //第二种用法 双引号用\1
    //$replacement = '1,3';        //第三种用法 单引号用 1
    
    
    //print preg_replace($pattern, $replacement, $string);
    
    /* Output
    April1,2003
    
    注:字符串单引号与双引号的区别,如果是双引号转义字符前要加,例如:"\1"='1'。
    */
    ?>

    4. preg_replace_callback : 执行一个正则表达式搜索并且使用一个回调进行替换

    <?php
    /* 一个unix样式的命令行过滤器, 用于将段落开始部分的大写字母转换为小写. */
    $fp = fopen("php://stdin", "r") or die("can't read stdin");
    while (!feof($fp)) {
        $line = fgets($fp);
        $line = preg_replace_callback(
            '|<p>s*w|',
            create_function(
                // single quotes are essential here,
                // or alternative escape all $ as $
                '$matches',
                'return strtolower($matches[0]);'
            ),
            $line
        );
        echo $line;
    }
    fclose($fp);
    ?> 
    <?php
    // 将文本中的年份增加一年.
    $text = "April fools day is 04/01/2002
    ";
    $text.= "Last christmas was 12/24/2001
    ";
    // 回调函数
    function next_year($matches)
    {
      // 通常: $matches[0]是完成的匹配
      // $matches[1]是第一个捕获子组的匹配
      // 以此类推
      return $matches[1].($matches[2]+1);
    }
    echo preg_replace_callback(
                "|(d{2}/d{2}/)(d{4})|",
                "next_year",
                $text);
    
    ?> 

     5. preg_split 使用正则分割。

    PREG_SPLIT_NO_EMPTY
    如果设定了本标记,则 preg_split() 只返回非空的成分。
    PREG_SPLIT_DELIM_CAPTURE
    如果设定了本标记,定界符模式中的括号表达式也会被捕获并返回。本标记添加于 PHP 4.0.5。
    PREG_SPLIT_OFFSET_CAPTURE
    如果设定了本标记,如果设定本标记,对每个出现的匹配结果也同时返回其附属的字符串偏移量。注意这改变了返回的数组的值,使其中的每个单元也是一个数组,其中第一项为匹配字符串,第二项为其在 subject 中的偏移量。本标记自 PHP 4.3.0 起可用。

  • 相关阅读:
    SVN报错working copy is not uptodate
    AndroidStudio中获得的VersionCode一直为1和VersionName一直为1.0
    OkHttp
    MockWebServer使用指南(转载)
    Android的Toolbar(含溢出菜单设置[弹出菜单的使用])的使用PopMenu的样式
    8-13笔记-安卓兼容
    自定义Dialog
    安卓圆角Button XML文件
    递归方法扫面文件夹(JAVA控制台程序)
    8月12笔记-安卓文件扫描
  • 原文地址:https://www.cnblogs.com/hubing/p/3148614.html
Copyright © 2020-2023  润新知