How does an excellent JS code be rewritten into PHP?

Source: Internet
Author: User
Keywords Php
Hsfzxjy This "17 line code implementation of simple Javascript string template" in the front-end is very useful, I would like to ask you how much PHP version should be rewritten.

function render(template, context) {    var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;    return template.replace(tokenReg, function (word, slash1, token, slash2) {        if (slash1 || slash2) {              return word.replace('\\', '');        }        var variables = token.replace(/\s/g, '').split('.');        var currentObject = context;        var i, length, variable;        for (i = 0, length = variables.length; i < length; ++i) {            variable = variables[i];            currentObject = currentObject[variable];            if (currentObject === undefined || currentObject === null) return '';        }        return currentObject;    })}

To hook a function to a String's prototype chain

String.prototype.render = function (context) {    return render(this, context);};

After that, we can call it this way:

"{greeting}! My name is { author.name }.".render({    greeting: "Hi",    author: {        name: "hsfzxjy"    }});// Hi! My name is hsfzxjy.

Reply content:

Hsfzxjy This "17 line code implementation of simple Javascript string template" in the front-end is very useful, I would like to ask you how much PHP version should be rewritten.

function render(template, context) {    var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;    return template.replace(tokenReg, function (word, slash1, token, slash2) {        if (slash1 || slash2) {              return word.replace('\\', '');        }        var variables = token.replace(/\s/g, '').split('.');        var currentObject = context;        var i, length, variable;        for (i = 0, length = variables.length; i < length; ++i) {            variable = variables[i];            currentObject = currentObject[variable];            if (currentObject === undefined || currentObject === null) return '';        }        return currentObject;    })}

To hook a function to a String's prototype chain

String.prototype.render = function (context) {    return render(this, context);};

After that, we can call it this way:

"{greeting}! My name is { author.name }.".render({    greeting: "Hi",    author: {        name: "hsfzxjy"    }});// Hi! My name is hsfzxjy.

To add, built-in functions strtr do almost as much as a touch, out of no support point syntax to access multiple layers outside


  
    'Hi',    '{author.name}' => 'hsfzxjy',));

In addition, it is absolutely impossible to modify the prototype chain of built-in objects in JavaScript.

Just a simple string substitution, write about 12 lines in PHP, as follows:

function render($template, $arr) {    $reg = "/(\\\)?\{([^\{\}\\\]+)(\\\)?\}/s";    return preg_replace_callback($reg, function ($m) use ($arr) {        if (!empty($m[1])||!empty($m[3])||empty($m[2])) return str_replace("\\", '', $m[0]);        $variables = explode('.', preg_replace("/\s/", '', $m[2]));        foreach ($variables as $variable) {            $arr = isset($arr[$variable])?$arr[$variable]:null;            if (!$arr) return '';        }        return $arr;    }, $template);}

Use is the same

$data = array(    "greeting"=> "Hi",    "author"=>array("name"=>"hsfzxjy"));echo render("{greeting}! My name is { author.name }.",$data);// Hi! My name is hsfzxjy.

On the side of PHP seems useless, if you need to search for a bit. PHP is usually written as "{$greeting}! My name is {$author [' name ']}, and also parse what to do. Smarty and so on the template also built this parsing, why do you want to do it again?

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.