zoukankan      html  css  js  c++  java
  • 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');
  • 相关阅读:
    php多态
    ssl certificate problem: self signed certificate in certificate chain
    test plugin
    open specific port on ubuntu
    junit vs testng
    jersey rest service
    toast master
    use curl to test java webservice
    update folder access
    elk
  • 原文地址:https://www.cnblogs.com/rainman/p/4498776.html
Copyright © 2011-2022 走看看