现在的位置: 网页制作教程网站制作教程 >正文
JavaScript脚本

JavaScript和PHP模仿C#中string.format效果

发表于2017/2/26 网站制作教程 0条评论 ⁄ 热度 1,158℃
目录导航

JavaScript和PHP分别模仿C#中string.format效果的代码。

1. JavaScript

function stringformat() {
var args = Array.prototype.slice.call(arguments);
if (args.length == 0) { return '';} 
if (args.length == 1) { return args[0]; } 
var str = args.shift();
return str.replace(
  /\\?\{([^{}]+)\}/g,
  function(match, name) {
    if (match.charAt(0) === '\\') {
      return match.slice(1);
    }
    return (args[name] === undefined) ? match : args[name];
  }
);
}
// 返回 my name is Rain Man and age is 28
stringformat('my name is {0} and age is {1}', 'Rain Man', 28, 'an');

2. PHP

function string_format() { 
  $args = func_get_args(); 
  if (count($args) == 0) { return '';} 
  if (count($args) == 1) { return $args[0]; } 
  $str = array_shift($args);
  $GLOBALS['OBJ'] = $args;
  $str = preg_replace_callback(
    '/\\\?{([^{}]+)}/', 
    function ($matches) {
      list($matche, $name) = $matches;
      if ($matche[0] === '\\') {
        return substr($matche, 1);
      }
      $obj = $GLOBALS['OBJ'];
      return isset($obj[$name]) ? $obj[$name] : $matche;
    },
    $str
  ); 
  $GLOBALS['OBJ'] = NULL;
  return $str;
}
// my name is Rain Man and age is 28
echo string_format('my name is {0} and age is {1}', 'Rain Man', 28, 'an');
  • 暂无评论