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');
posted @ 2015-05-12 21:59  Rain Man  阅读(1882)  评论(0编辑  收藏  举报