Skip to content

Instantly share code, notes, and snippets.

@lcherone lcherone/index.md
Created May 19, 2019

Embed
What would you like to do?
Template variable replacement, js and php

In PHP

<?php
$vars = [
  'name' => 'Loz'
];

$template = 'Hello {{ name }}!';

$result = preg_replace_callback('/{{[ ]{0,}([\w\_-]{1,})[ ]{0,}}}/', function ($match) use ($vars) {
  return array_key_exists($match[1], $vars) ? $vars[$match[1]] : '';
}, $template);

echo $result;

In JS

let vars = {
    name: 'Loz'
}

let template = 'Hello {{ name }}!'

let result = template.replace(/\{\{[ ]{0,}([\w\_-]{1,})[ ]{0,}\}\}/gi, function (...match) {
    return typeof vars[match[1]] !== 'undefined' ? vars[match[1]] : ''
})

console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.