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
- <?php
- $prefix = ' prefix ';
- $name = ' subject name ';
- $postfix = ' suffix ';
- $title = ' {$prefix} {$name} Latest news {$postfix} ';
- $match = Array ();
- Preg_match_all ('/{\$ (. *?)} /', $title, $match);
- foreach ($match [1] as $key = + $value) {
- if (isset ($$value)) {
- $title = str_replace ($match [0][$key], $$value, $title);
- }
- }
- echo $title;
Variable name resolution in PHP custom strings