Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6236331
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T10:50:03+00:00 2026-05-24T10:50:03+00:00

I have a mail script that I use in one of my projects, and

  • 0

I have a mail script that I use in one of my projects, and I’d like to allow customization of this letter. the problem is that parts of the email are dynamically generated from the database. I have predefined tokens that I use to describe what should replace the token, but I’d like to simplify this but writing a better parser that can interpret the token and figure out which variable to use to replace it.

Right now I have a very large array with all the possible tokens and their corresponding values, like so:

$tokens['[property_name]'] = $this->name;

and then I run through the template and replace any instance of the key with it’s value.

I’d prefer to just run through the template, look for [] or whatever I use to define a token, and then read what’s inside and convert that to a variable name.

I need to be able to match a few levels of relationships so $this->account->owner->name;
as an example, and I need to be able to reference methods. $this->account->calcTotal();

I thought I might be able to take the example [property_name] and replace the instance of _ with -> and then call that as a variable, but I don’t believe it works with methods.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T10:50:04+00:00Added an answer on May 24, 2026 at 10:50 am

    You’re creating sort of a template system. You can either re-invent the wheel (sort of) by coding this on your own or just using a lighweight template system like mustache.

    For a very lightweight approach you can make use of regular expressions to formulate the syntax of your template variables. Just define how a variable can be written, then extract the names/labels used and replace it at will.

    A function to use for this is preg_replace_callback. Here is some little example code (Demo) which only reflects simple substitution, however, you can modify the replace routine to access the values you need (in this example, I’m using a variable that is either an Array or implements ArrayAccess):

    <?php
    $template = <<<EOD
    This is my template,
    
    I can use [vars] at free [will].
    EOD;
    
    class Template
    {
        private $template;
        private $vars;
        public function __construct($template, $vars)
        {
            $this->template = $template;
            $this->vars = $vars;
        }
        public function replace(array $matches)
        {
            list(, $var) = $matches;
            if (isset($this->vars[$var]))
            {
                 return $this->vars[$var];
            }
            return sprintf('<<undefined:%s>>', $var);
    
        }
        public function substituteVars()
        {
            $pattern = '~\[([a-z_]{3,})\]~';
            $callback = array($this, 'replace');
            return preg_replace_callback($pattern, $callback, $this->template );
        }
    
    }
    
    $templ = new Template($template, array('vars' => 'variables'));
    
    echo $templ->substituteVars();
    

    This does not look spectacular so far, it’s just substituting the template tags to a value. However, as already mentioned you can now inject a resolver into the template that can resolve template tags to a value instead of using an simple array.

    You’ve outlined in your question that you would like to use the _ symbol to separate from object members / functions. The following is a resolver class that will resolve all global variables to that notation. It shows how to handle both, object members and methods and how to traverse variables. However, it does not resolve to $this but to the global namespace:

    /**
     * Resolve template variables from the global namespace
     */
    class GlobalResolver implements ArrayAccess 
    {
        private function resolve($offset)
        {
            $stack = explode('_', $offset);
    
            return $this->resolveOn($stack, $GLOBALS);
        }
    
        private function resolveOn($stack, $base)
        {
            $c = count($stack);
            if (!$c)
                return array(false, NULL);
    
            $var = array_shift($stack);
            $varIsset = isset($base[$var]);
    
            # non-set variables don't count
            if (!$varIsset)
            {
                return array($varIsset, NULL);
            }
    
            # simple variable
            if (1 === $c)
            {
                return array($varIsset, $base[$var]);
            }
    
            # descendant    
            $operator = $stack[0];
            $subject = $base[$var];
            $desc = $this->resolvePair($subject, $operator);
    
            if (2 === $c || !$desc[0])
                return $desc;
    
            $base = array($operator => $desc[1]);
            return $this->resolveOn($stack, $base);
        }
    
        private function resolvePair($subject, $operator)
        {
            if (is_object($subject))
            {
                if (property_exists($subject, $operator))
                {
                    return array(true, $subject->$operator);
                }
                if (method_exists($subject, $operator))
                {
                    return array(true, $subject->$operator());
                }
            }
            if (is_array($subject))
            {
                if (array_key_exists($operator, $subject))
                {
                    return array(true, $subject[$operator]);
                }
            }
            return array(false, NULL);
        }
    
        public function offsetExists($offset)
        {
            list($isset) = $this->resolve($offset);
            return $isset;
        }
        public function offsetGet($offset)
        {
            list($isset, $value) = $this->resolve($offset);
            return $value;
        }
        public function offsetSet ($offset, $value)
        {
            throw new BadMethodCallException('Read only.');
        }
        public function offsetUnset($offset)
        {
            throw new BadMethodCallException('Read only.');
        }
    }
    

    This resolver class can be used then to make use of some example values:

    /**
     * fill the global namespace with some classes and variables
     */
    class Foo
    {
       public $member = 'object member';
       public function func()
       {
           return 'function result';
       }
       public function child()
       {
           $child->member = 'child member';
           return $child;
       }
    }
    
    $vars = 'variables';
    $foo = new Foo;
    
    $template = <<<EOD
    This is my template,
    
    I can use [vars] at free [foo_func] or [foo_member] and even [foo_child_member].
    EOD;
    
    /**
     * this time use the template with it's own resolver class
     */
    $templ = new Template($template, new GlobalResolver);
    
    echo $templ->substituteVars();
    

    See the full demo in action.

    This will only need a slight modification to fit your needs then finally.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a php script that i use to send mail to customers. How
I have a script that access the specified email and fetches mail. $temp->getContent() echos
I have written a PHP script that I use for authentication with e-mail and
I have a PHP email script on my website that potential clients use to
I have this mail script I have to run a few times. To start
We currently have a working php mail script, this works fine and as we
I have a phone system that calls a PHP script to send an email
I have a small script that I wrote to send an email out to
I have a simple PHP script that sends a message to a specified email
I have an init.d script that looks like: #!/bin/bash # chkconfig 345 85 60

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.