Skip to content

Instantly share code, notes, and snippets.

@Paradoxis
Last active March 14, 2022 13:30
Show Gist options
  • Save Paradoxis/db7ca9fdd88a53d7540bc183611567bc to your computer and use it in GitHub Desktop.
Save Paradoxis/db7ca9fdd88a53d7540bc183611567bc to your computer and use it in GitHub Desktop.
Find and replace double curly braces in PHP, example: findReplace("Hello, {{ name }}", "name", "John"); // "Hello, John" Raw
<?php
/**
* Parses a template argument to the specified value
* Template variables are defined using double curly brackets: {{ [a-zA-Z] }}
* Returns the query back once the instances has been replaced
* @param string $string
* @param string $find
* @param string $replace
* @return string
* @throws \Exception
*/
function findReplace($string, $find, $replace)
{
if (preg_match("/[a-zA-Z\_]+/", $find)) {
return (string) preg_replace("/\{\{(\s+)?($find)(\s+)?\}\}/", $replace, $string);
} else {
throw new \Exception("Find statement must match regex pattern: /[a-zA-Z]+/");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment