preg_replace_callback使用方法

官网解释:

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

(PHP 4 >= 4.0.5, PHP 5)

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

作为程序,这个时候,亲测比看文字介绍要管用的多

实例:

<?php
// 将文本中的年份增加一年.
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// 回调函数
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() ;

 

posted on 2016-11-26 14:56  爱吃柠檬不加糖  阅读(2111)  评论(0编辑  收藏  举报

导航