douqian9729 2014-03-13 12:00
浏览 33
已采纳

在php中搜索和替换令牌

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) . "
";
  • 写回答

1条回答 默认 最新

  • duanou2016 2014-03-13 12:06
    关注

    Just try with:

    function phpSupplant($string, $obj)
    {
      $keys = array_map(function($key){ return '{{' . $key . '}}'; }, array_keys($obj));
      return str_replace($keys, $obj, $string);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀