Skip to content

Instantly share code, notes, and snippets.

@davidhemphill
Last active October 14, 2018 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save davidhemphill/fe1e7e84486410cd69462bfe23ed6d0b to your computer and use it in GitHub Desktop.
Save davidhemphill/fe1e7e84486410cd69462bfe23ed6d0b 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)
{
$data = $this->getData();
// For each item in the data array, replace the token with the variable's content
collect($data)->each(function ($item, $key) use (&$text, $data) {
$text = str_replace($this->formatToken($key), $data[$key], $text);
});
return $text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment