zoukankan      html  css  js  c++  java
  • preg_replace_callback使用方法

    官网解释:

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

    (PHP 4 >= 4.0.5, PHP 5)

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

    具体应用:

    class StringUtil {
        function replaceAll($sTemplate ) {
            $resp = preg_replace_callback(
                '/{(.*?)}/'
                ,function ($matches) {
                    if (2 == count($matches)) {
                        return $this->$matches[1] ;
                    } else {
                        return "" ;
                    }
                }
                ,$sTemplate
            ) ;
            return $resp ;
        }
    }
    
    function _test() {
        $sql_t = "select t_id, ware_name from dyw_ware where t_id = {t_id} {orderby}" ;
        $obj = new StringUtil() ;
        $obj->t_id = 101 ;
        $obj->orderby = "order by t_id desc" ;
        $sql =  $obj->replaceAll($sql_t) ;
        echo "<br/>".$sql ;
    
    }
    _test() ;
  • 相关阅读:
    汇编学习笔记(一)
    外部中断的资料
    喇叭的落幕
    红外模块
    SQL2005连接不上解决
    DataGrid中动态添加列,使用CheckBox选择行
    List和ObservableCollection的相互转化
    使用C#发送邮件
    C#委托与事件 简明
    Linq GroupBy 求和
  • 原文地址:https://www.cnblogs.com/wanghaokun/p/6104206.html
Copyright © 2011-2022 走看看