Last active
March 14, 2022 13:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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