Skip to content

Instantly share code, notes, and snippets.

@NimzyMaina
Last active December 6, 2019 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NimzyMaina/b289da32182b8ba9064bac8b6cc4a630 to your computer and use it in GitHub Desktop.
Save NimzyMaina/b289da32182b8ba9064bac8b6cc4a630 to your computer and use it in GitHub Desktop.
How to replace place holders in an SMS template in PHP
<?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