Last active
October 14, 2018 13:02
-
-
Save davidhemphill/fe1e7e84486410cd69462bfe23ed6d0b to your computer and use it in GitHub Desktop.
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 | |
$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!"; |
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 | |
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