zoukankan      html  css  js  c++  java
  • preg_replace_callback 正则替换回调方法用法,

    Example #1 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|',
            function ($matches) {
                return strtolower($matches[0]);
            },
            $line
        );
        echo $line;
    }
    fclose($fp);
    ?>
    

      

    Example #2 preg_replace_callback()示例
    
    <?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);
    
    ?>
    

      

    Example #3 preg_replace_callback()使用递归构造处理BB码的封装
    
    <?php
    $input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";
    
    function parseTagsRecursive($input)
    {
         /* 译注: 对此正则表达式分段分析
         * 首尾两个#是正则分隔符
         * [indent] 匹配一个原文的[indent]
         * ((?:[^[]|[(?!/?indent])|(?R))+)分析:
         *   (?:[^[]|[(?!/?indent])分析:
         *  首先它是一个非捕获子组
         *   两个可选路径, 一个是非[字符, 另一个是[字符但后面紧跟着不是/indent或indent.
         *   (?R) 正则表达式递归
         *     [/indent] 匹配结束的[/indent]
         * /
    
        $regex = '#[indent]((?:[^[]|[(?!/?indent])|(?R))+)[/indent]#';
    
        if (is_array($input)) {
            $input = '<div style="margin-left: 10px">'.$input[1].'</div>';
        }
    
        return preg_replace_callback($regex, 'parseTagsRecursive', $input);
    }
    
    $output = parseTagsRecursive($input);
    
    echo $output;
    ?>
    

      

  • 相关阅读:
    165. Compare Version Numbers
    164. Maximum Gap
    3、桶排序
    162. Find Peak Element
    160. Intersection of Two Linked Lists
    155. Min Stack
    154. Find Minimum in Rotated Sorted Array II
    153. Find Minimum in Rotated Sorted Array
    Linux/Unix系统编程手册 第二章:基本概念
    Linux/Unix系统编程手册 第一章:历史和标准
  • 原文地址:https://www.cnblogs.com/chengzhi59/p/6980566.html
Copyright © 2011-2022 走看看