/**
   * Interpolates context values into the message placeholders.
   */
  function interpolate($message, array $context = array())
  {
      // build a replacement array with braces around the context keys
      $replace = array();
      foreach ($context as $key => $val) {
          // check that the value can be casted to string
          if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
              $replace['{' . $key . '}'] = $val;
          }
      }

      // interpolate replacement values into the message and return
      return strtr($message, $replace);
  }

  // a message with brace-delimited placeholder names
  $message = "User {username} created";

  // a context array of placeholder names => replacement values
  $context = array('username' => 'bolivar');

  // echoes "User bolivar created"
  echo interpolate($message, $context);

Leave a reply:

Your email address will not be published.

Site Footer

Sliding Sidebar

About Me

About Me

Hello, my name is Dũng (Johnny). Welcome to my blog.

As I’m a developer, I write about topics related to the field of programming, mainly from a technical point of view. On this blog you’ll find posts which encourage discussion, information about development trends, case studies, reviews, tutorials, tips on how to improve your effectiveness, and anything else that might be fascinating to people from the IT industry.
I love PHP, NodeJS,... and Fullstack.