Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Forked from davidhemphill/Marge.php
Last active September 19, 2023 13:11
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save adamwathan/d3cea4e168e6d9e9111f03d254ff2f8c to your computer and use it in GitHub Desktop.
Save adamwathan/d3cea4e168e6d9e9111f03d254ff2f8c to your computer and use it in GitHub Desktop.
<?php
$marge = new Marge();
$marge->setData([
'first_name' => 'David',
'last_name' => 'Hemphill',
]);
$marge->replace("Thanks, [FIRST_NAME] [LAST_NAME] for doing yer thang!");
// Desired result
"Thanks David Hemphill for doing yer thang!";
<?php
namespace App\Merge;
class Marge
{
protected $data = [];
public function setData($data)
{
$this->data = $data;
return $this;
}
public function getData()
{
return $this->data;
}
protected function addDelimiters($token)
{
return '[' . $token . ']';
}
protected function formatToken($token)
{
return $this->addDelimiters(strtoupper($token));
}
public function replace($text)
{
return collect($this->getData())->map(function ($item, $key) {
return [$this->formatToken($key), $item];
})->reduce(function ($text, $replacement) {
list($search, $replace) = $replacement;
return str_replace($search, $replace, $text);
}, $text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment