Replace multiple placeholders with PHP?

后端 未结 3 653
忘了有多久
忘了有多久 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);
    

提交回复
热议问题