一、简单替换:
- javascript:
a. 代码:var data = { ‘name‘:‘lee‘, ‘place‘:‘wuhan‘ } var str = "Hello {{name}}, Welcome to {{place}}!"; var res = str.replace( /{{([\s\S]+?)}}/g, function(param1,param2){ var index = param2 return data[index] } ); console.log(res)
b. 输出:
Hello lee, Welcome to wuhan!
- php:
a. 代码:<?php $data = array( ‘name‘=>‘lee‘, ‘place‘=>‘wuhan‘ ); $str = "Hello {{name}}, Welcome to {{place}}!"; $res = preg_replace_callback( "/{{([\s\S]+?)}}/", function($param) use($data){ $index = $param[1]; return $data[$index]; }, $str ); echo $res;
b. 输出:
Hello lee, Welcome to wuhan!
二、复杂替换:
- javascript:
a. 代码:var data = { ‘name‘:‘lee‘, ‘place‘:‘wuhan‘ } var str = "Hello {{data.name}}, Welcome to {{data.place}}!"; var res = str.replace( /{{([\s\S]+?)}}/g, function(param1,param2){ var ret = eval(param2) return ret } ); console.log(res)
b. 输出:
Hello lee, Welcome to wuhan!
- php:
a. 代码:<?php $data = array( ‘name‘=>‘lee‘, ‘place‘=>‘wuhan‘ ); $str = "Hello {{data.name}}, Welcome to {{data.place}}!"; $res = preg_replace_callback( "/{{([\s\S]+?)}}/", function($param) use($data){ $raw = $param[1]; $arr = explode(‘.‘,$raw); $command = ‘return ‘.‘$‘.$arr[0].‘[\‘‘.$arr[1].‘\‘];‘; $ret = eval($command); return $ret; }, $str ); echo $res;
b. 输出:
Hello lee, Welcome to wuhan!
原文地址:http://blog.51cto.com/12173069/2104231
时间: 2024-10-14 00:03:54