dsh1102 2011-07-30 20:46
浏览 62
已采纳

使用preg_replace_callback时出现问题

i have a problem when i use preg_replace_callback. i have google translator class and i want to translate all matches using it .

the code was .

$code = preg_replace_callback('/_e\(\'(.*?)\'\)/',create_function(
'$matches',
'return $translator->translate($matches);'),
$code);

when i make var dump for the var $code, i found its string"1" !!!

im sure that im using a right way for the class.

Thanks.

  • 写回答

3条回答 默认 最新

  • dongzongxun8491 2011-07-30 22:16
    关注

    The problem here is scope. Something similar to this would work in JavaScript, but JS and PHP handle scope differently. To access $translator from within the anonymous function's scope, you need to declare it as a global.

    <?php
    $code = preg_replace_callback('/_e\(\'(.*?)\'\)/',
                create_function('$matches',
                    'global $translator;'.
                    'return $translator->translate($matches);'),
                $code);
    ?>
    

    If you want to keep the anon as a one-liner, you can use the globals array:

    <?php
    $code = preg_replace_callback('/_e\(\'(.*?)\'\)/',
                create_function('$matches',
                    "return $GLOBALS['translator']->translate($matches);"),
                $code);
    ?>
    

    If you have PHP 5.3.0 or later, this can be alleviated with closures and use:

    <?php
    $code = preg_replace_callback('/_e\(\'(.*?)\'\)/',
                function($matches) use ($translator) {
                    return $translator->translate($matches);
                }, $code);
    ?>
    

    This is assuming that $translator was created in the same scope as $code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下