在php中搜索和替换令牌

时间:2014-03-13 12:00:57

标签: php

我遇到了一个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;
}

使用方法:

// 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) . "\n";

1 个答案:

答案 0 :(得分:0)

试试:

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