Last active
December 6, 2019 15:03
-
-
Save NimzyMaina/b289da32182b8ba9064bac8b6cc4a630 to your computer and use it in GitHub Desktop.
How to replace place holders in an SMS template in PHP
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 | |
$msg = 'Dear {{BNAME}}, your loan of KES {{AMOUNT}} has been fully repaid.'; | |
function wrap($str) | |
{ | |
return "{{{$str}}}"; | |
} | |
function parse($msg,array $placeholders) | |
{ | |
foreach($placeholders as $k => $v){ | |
if(!strstr($msg,wrap($k))) { | |
throw new Exception("Unable to parse template - $k is not present."); | |
} | |
$msg = strtr($msg, [ wrap($k) => $v]); | |
} | |
$matches = []; | |
$pattern = "/".preg_quote("{{").".*?".preg_quote("}}")."/"; | |
preg_match($pattern, $msg, $matches); | |
if (count($matches) > 0) { | |
throw new Exception("Could not find a replacement for ".$matches[0], 1); | |
} | |
return $msg; | |
} | |
try{ | |
echo parse($msg,[ | |
'BNAME' => 'Nimrod', | |
'AMOUNT' => number_format(1000,0), | |
//'AMOUN' => number_format(1000,0), | |
//'Other' => 'sdfefe' | |
]); | |
} | |
catch(Exception $e){ | |
echo $e->getMessage(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment