I've come across a javascript supplant method and would like to implement it in php. I came up with this function. Feel free to check if this function works or not. I welcome any comment or suggestion to help me improve in developing.
function phpSupplant($string, $obj)
{
preg_match_all('/{([^{}]*)}/', $string, $matches, PREG_PATTERN_ORDER);
$newString = preg_replace_callback(
'/{{([^{}]*)}}/',
function ($matches) use( &$obj){
return $obj[$matches[1]];
},
$string);
return $newString;
}
How to use:
//string
$sample = "*Working in an apple plant {{were}} the worst job {{you}} ever had. First of all, the work
was physically hard. For ten hours a night, {{you}} took cartons that rolled down a metal
track and stacked them onto wooden stands in a tractor,trailer. Each carton
contained twenty,five pounds of bottled apple juice, and they came down the track
fast. The second bad feature of the job {{were}} the pay. {{you}} {{were}} getting the minimum wage
at that time, $3.25 an hour. {{you}} had to work over sixty hours a week to get a decent
take,home pay. Finally, {{you}} hated the working conditions. We were limited to two ten,
minute breaks and an unpaid half hour for lunch. Most of my time
{{were}} spent outside
loading dock in the freezing cold. {{you}} {{were}} very lonely on the job because {{you}} had no
interests in common with the other workers. {{you}} felt this isolation especially when the
production line shut down for the night, and {{you}} spent two hours by myself cleaning
the apple vats. The vats were an ugly place to be on a cold morning, and the job {{were}}
a bitter one to have";
$obj = array('were' => 'was', 'you' => 'I');
echo phpSupplant($sample, $obj) . "
";