Skip to content

Instantly share code, notes, and snippets.

@lcherone
Created May 19, 2019 05:53
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lcherone/f7ef70406c7c84aeb7d64566afb63bb8 to your computer and use it in GitHub Desktop.
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