2017-05-19 19:55 阅读 48

如何在PHP / MySQL应用程序中创建合并标签?

I'm writing a PHP/MYSQL SaaS app and I'm currently working on email functionality (using Swift). I plan to save email templates to the MySQL database (each tenant will be able to customize them). However, I also need to include dynamic data in the templates ("merge tags" like first name and last name). I tried simply storing {$test} in the DB but that didn't work. Is there something I need to do after pulling the data from MySQL to merge variables into the text before passing it to Swift?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douqiju2520 douqiju2520 2017-05-19 21:02

    I'm not familiar with the Swift library, but a quick glance at the documentation didn't turn up anything about parsing messages to insert variables. That means you'll likely need to do that yourself.

    One way you might do it, is to come up with your own (arbitrary) syntax for holding a variable's position in a message. For example, you might want to use {%VAR_NAME%} or something.

    So you can save your templates like:

    Hello {%recipient_name%},

    This is to inform you that invoice #{%invoice_num%} is available as of {%invoice_date%}.

    Thank you, {%sender_name%}

    And then, assuming that template is stored in $email_body, you could do a string replace (either str_replace(), or something like preg_replace(). For something this simple, I wouldn't suggest bogging things down with a regular expression search). Below is an example of how you might go about doing it. You can build the $search and $replace arrays however you would like, but I just laid it out like this to be more human readable.

    // Original body:
    $email_body = "Hello {%recipient_name%},
                   This is to inform you that invoice #{%invoice_num%} is available as of {%invoice_date%}.
                   Thank you, {%sender_name%}";
    // Easily readable input values
    $values = array(
        'recipient_name'    => $db_value['recipient_name'],
        'invoice_num'       => $db_value['invoice_num'],
        'invoice_date'      => date("Y-m-d"),
        'sender_name'       => $_SESSION['user_name']
    // Break it up into the search and replace arrays
    $search = array();
    $replace = array();
    foreach ($values AS $index => $value)
        $search[] = "{%" . $index . "%}"; // Wrapping the text in "{%...%}"
        $replace[] = $value;
    // Do the replacement
    $email_body = str_replace($search, $replace, $email_body);

    The main idea here is that you will be replacing placeholders with a specific syntax (eg {%VALUE%}) with a real value. How you generate the $search and $replace variables is up to you.

    This will output something like:

    Hello Foo,

    This is to inform you that invoice #123456 is available as of 2017-05-19.

    Thank you, Bar

    点赞 评论 复制链接分享