doukekui0914 2012-10-01 03:00
浏览 20
已采纳

智能使用PHP str_replace(或类似的东西)

There are a large numbers of PHP variables I use in my template files and some of them need to be accessible for editors who can only use HTML. What I want to do exactly is have them identify the variable doing something like [ITEM_NAME_1] when typing/editing content, and PHP finds them because they are wrapped in brackets, and replaces them with the appropriate PHP variable (in that case, $ITEM_NAME_1)

The content of each page is in a variable "$page_content", so right now the only way I know how to accomplish is to manually write lines to replace what I need.

$page_content = str_replace("[ITEM_NAME_1]", "$ITEM_NAME_1", "$page_content"); 
print $page_content

The issue is there are hundreds of these "ITEM_NAME_X" variables and I don't want to have to create a massive repeat of "str_replace" lines manually for each ITEM_NAME_X.

What I want to accomplish is have PHP find anything inside $page_content that is wrapped in brackets [], take the name from inside the bracket and replace all of it with the variable of that bracketted name. So if it finds [ITEM_5], it replaces it with $ITEM_5. Is this at all possible? Let me know, thanks.

  • 写回答

3条回答 默认 最新

  • dongmen5867 2012-10-01 03:06
    关注

    Give preg_replace with the /e modifier a whirl. Combine that with variable variable name syntax to get the effect you want.

    $page_content = preg_replace('/\[(.*?)\]/e', '$$1', $page_content);
    

    This uses a regex to match strings between square brackets. The strings are captured and are accessed with $1 in the replacement string. The second $ looks up the variable named with whatever's in $1.

    If you want to do something more complicated with the replacement, you can invoke your own function from the replacement string. For example:

    function substitute_tag($tag_name)
    {
        $replacement_values = array('foo' => 'bar', 'baz' => '42', ...);
        return $replacement_values[$tag_name];
    }
    
    $page_content = preg_replace('/\[(.*?)\]/e', 'substitute_tag("$1")', $page_content);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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