在php中搜索和替换令牌

在php中搜索和替换令牌,php,Php,我遇到了一个javascript替代方法,并希望在php中实现它。我提出了这个函数。请随时检查此功能是否有效。我欢迎任何意见或建议,以帮助我提高发展 function phpSupplant($string, $obj) { preg_match_all('/{([^{}]*)}/', $string, $matches, PREG_PATTERN_ORDER); $newString = preg_replace_callback( '/{{([^{}]

我遇到了一个javascript替代方法,并希望在php中实现它。我提出了这个函数。请随时检查此功能是否有效。我欢迎任何意见或建议,以帮助我提高发展

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;
}
如何使用:

//串

$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) . "\n";
试一下:

function phpSupplant($string, $obj)
{
  $keys = array_map(function($key){ return '{{' . $key . '}}'; }, array_keys($obj));
  return str_replace($keys, $obj, $string);
}

你有什么问题?有问题吗?我的错。我的问题是,如果创建的函数作为javascript的php替代品,那么您应该编辑您的问题,以便清楚地了解您的要求。这是一种方法。谢谢hsz的回答。但是我的函数产生的结果和你的一样吗?酷。谢谢你的测试,谢谢你的功能。如果你觉得我的答案有帮助的话,记得用左边的粗线来接受它。