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;
    ?>
    

      

  • 相关阅读:
    使用git遇到的一些问题
    小程序的生命周期
    git status -s命令解析
    JavaScript 关闭浏览器窗口
    JavaScript 如何编写计算器
    JavaScript 数组对象的去重
    JavaScript 数组排序(从大到小,从小到大)
    JavaScript 常用的Math对象
    JavaScript 获取 当前日期和三十天以前日期
    JavaScript 获取数组的最大值和最小值
  • 原文地址:https://www.cnblogs.com/chengzhi59/p/6980566.html
Copyright © 2011-2022 走看看