Variable name resolution in PHP custom strings

Source: Internet
Author: User
Tags vars

variable name resolution in PHP custom strings 

Such a requirement: the title of the page can be customized in the background, the custom content may contain variables, variables are represented by {$var}, where $var is the variable name

Put the title field into the database, and then put forward, with PHP's own variable name resolution is used, will be directly output {$var}, not as in the definition of strings, when using double quotation marks when the {$var} is automatically transformed into the corresponding variable content, this is like a single quote definition of the string, So you need to parse it yourself.

The idea here is to use regular expressions to extract all {$var} from the string, and then determine if there is a corresponding variable, and if so, replace the content with Str_replace ().

The procedure is as follows:

[PHP]View Plaincopy
  1. <?php
  2. $prefix = ' prefix ';
  3. $name = ' subject name ';
  4. $postfix = ' suffix ';
  5. $title = ' {$prefix} {$name} Latest news {$postfix} ';
  6. $match = Array ();
  7. Preg_match_all ('/{\$ (. *?)}  /', $title, $match);
  8. foreach ($match [1] as $key = + $value) {
  9. if (isset ($$value)) {
  10. $title = str_replace ($match [0][$key], $$value, $title);
  11. }
  12. }
  13. echo $title;

Variable name resolution in PHP custom strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.