duanjuduo4573 2011-09-18 11:48
浏览 63
已采纳

如何在php中使用preg_replace用函数结果替换文本?

I have a complicated problem: I have a very long text and I need to call some php functions inside my text. The function name is myfunction(); I`we included in my text the function in the following way: " text text text myfunction[1,2,3,4,5]; more text text ... "

And I want to replace each myfunction[...] with the result of the function myfunction with the variables from the [] brackets.

my code is:

<?php echo preg_replace('/myfunction[[0-9,]+]/i',myfunction($1),$post['content']); ?>

,but it`s not working.

The parameter should be an array, because it can contain any number of values.

  • 写回答

3条回答 默认 最新

  • douzhangli9563 2011-09-18 12:01
    关注

    If I were you, I would avoid using the e modifier to preg_replace because it can lead you open to execution of arbitrary code. Use preg_replace_callback instead. It's slightly more verbose, but much more effective:

    echo preg_replace_callback('/myfunction\[([0-9,]+)\]/i', function($matches) {
        $args = explode(',', $matches[1]); // separate the arguments
        return call_user_func_array('myfunction', $args); // pass the arguments to myfunction
    }, $post['content']);
    

    This uses an anonymous function. This functionality won't be available to you if you use a version of PHP before 5.3. You'll have to create a named function and use that instead, as per the instructions on the manual page.

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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历