dtsc1684 2010-07-01 14:29
浏览 18

简单的模板var替换,但扭曲

So I'm setting up a system that has a lot of emails, and variable replacement within it, so I'm writing a class to manage some variable replacement for templates stored in the database.

Here's a brief example:

// template is stored in db, so that's how this would get loaded in 
$template = "Hello, %customer_name%, thank you for contacting %website_name%"; 
// The array of replacements is built manually and passed to the class 
// with actual values being called from db 
$replacements = array('%customer_name%'=>'Bob', '%website_name%'=>'Acme'); 
$rendered = str_replace(array_keys($replacements), $replacements, $template); 

Now, that works well and good for single var replacements, basic stuff. However, there are some places where there should be a for loop, and I'm lost how to implement it.

The idea is there'd be a template like this:

"hello, %customer_name%, thank you for requesting information on {products}"

Where, {products} would be an array passed to the template, which the is looped over for products requested, with a format like:

Our product %product_name% has a cost of %product_price%. Learn more at %product_url%.

So an example rendered version of this would be:

"hello, bob, thank you for requesting information on:

Our product WidgetA has a cost of $1. Learn more at example/A

Our product WidgetB has a cost of $2. Learn more at example/B

Our product WidgetC has a cost of $3. Learn more at example/C.

What's the best way to accomplish this?

  • 写回答

2条回答 默认 最新

  • drlu11748 2010-07-01 14:43
    关注
    $products = array('...');
    function parse_products($matches)
    {
        global $products;
        $str = '';
        foreach($products as $product) {
           $str .= str_replace('%product_name%', $product, $matches[1]); // $matches[1] is whatever is between {products} and {/products}
        }
        return $str;
    }
    
    $str = preg_replace_callback('#\{products}(.*)\{/products}#s', 'parse_products', $str);
    

    The idea is to find string between {products} and {products}, pass it to some function, do whatever you need to do with it, iterating over $products array. Whatever the function returns replaces whole "{products}[anything here]{/products}".

    The input string would look like that:

    Requested products: {products}%product_name%{/products}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题