Simple template var replacement, but with a twist

后端 未结 2 1721
轮回少年
轮回少年 2020-12-22 02:12

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

2条回答
  •  别那么骄傲
    2020-12-22 02:36

    $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}
    

提交回复
热议问题