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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。