Replace multiple placeholders with PHP?

后端 未结 3 562
忘了有多久
忘了有多久 2020-12-09 14:24

I have a function that sends out site emails (using phpmailer), what I want to do is basically for php to replace all the placheholders in the email.tpl file with content th

相关标签:
3条回答
  • 2020-12-09 14:46

    Simple, see strtr­Docs:

    $vars = array(
        "[{USERNAME}]" => $username,
        "[{EMAIL}]" => $email,
    );
    
    $message = strtr($message, $vars);
    

    Add as many (or as less) replacement-pairs as you like. But I suggest, you process the template before you call the phpmailer function, so things are kept apart: templating and mail sending:

    class MessageTemplateFile
    {
        /**
         * @var string
         */
        private $file;
        /**
         * @var string[] varname => string value
         */
        private $vars;
    
        public function __construct($file, array $vars = array())
        {
            $this->file = (string)$file;
            $this->setVars($vars);
        }
    
        public function setVars(array $vars)
        {
            $this->vars = $vars;
        }
    
        public function getTemplateText()
        {
            return file_get_contents($this->file);
        }
    
        public function __toString()
        {
            return strtr($this->getTemplateText(), $this->getReplacementPairs());
        }
    
        private function getReplacementPairs()
        {
            $pairs = array();
            foreach ($this->vars as $name => $value)
            {
                $key = sprintf('[{%s}]', strtoupper($name));
                $pairs[$key] = (string)$value;
            }
            return $pairs;
        }
    }
    

    Usage can be greatly simplified then, and you can pass the whole template to any function that needs string input.

    $vars = compact('username', 'message');
    $message = new MessageTemplateFile('email.tpl', $vars);
    
    0 讨论(0)
  • 2020-12-09 14:48

    Why dont you just make the email template a php file aswell? Then you can do something like:

    Hello <?=$name?>, my name is <?=$your_name?>, today is <?=$date?>
    

    inside the email to generate your HTML, then send the result as an email.

    Seems to me like your going about it the hard way?

    0 讨论(0)
  • 2020-12-09 14:53

    The PHP solutions can be:

    • usage of simple %placeholder% replacement mechanisms:
      • str_replace,
      • strtr,
      • preg_replace
    • use of pure PHP templating and conditional logic (short open tags in PHP and alternative syntax for control structures)

    Please, find the wide answer at Programmers.StackExchange to find out other approaches on PHP email templating.

    0 讨论(0)
提交回复
热议问题