PHP 自定义字符串中的变量名解析

WBOY
Release: 2016-06-23 13:59:30
Original
1249 people have browsed it

这样一个需求:页面的 title 可以在后台自定义,自定义内容中可能包含变量,变量用 {$var} 表示, 其中 $var 为变量名

将 title 字段存入数据库中,再提出来之后,用php自己的变量名解析就不管用了,会直接输出 {$var} ,不会像在定义字符串的时候,用双引号时就会自动把 {$var} 变换成相应的变量内容,这里就像是用单引号定义的字符串,所以需要自己解析。

这里的思路是用正则表达式把字符串中的所有 {$var} 提取出来,然后判断是否存在相应的变量,如果存在,用 str_replace() 替换相应的内容

程序如下:

<?php $prefix = '前缀';$name = '主题名称';$postfix = '后缀';$title = '{$prefix} {$name} 最新新闻 {$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;
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!