Home > Backend Development > PHP Tutorial > 怎么从参数文件中读取内容并替换变量值

怎么从参数文件中读取内容并替换变量值

WBOY
Release: 2016-06-13 12:18:57
Original
1029 people have browsed it

如何从参数文件中读取内容并替换变量值
A.TXT内容如下
01:富裕
02:一般
03:贫穷

C.TXT内容如下
01:中国
02:美国
03:德国
04:法国
05:葡萄牙

php文件中
$a1=02
$a2=01
$a3=03

$c1=01
$c2=03
$c3=05


请问如何将a开头的变量都替换成A.TXT中的富裕程度,将c开头的变量都替换成国家名字?

------解决思路----------------------
file_get_contents函数读取txt内容
首先explode("\r\n", $txt)分行
遍历上一步结果,再用explode拆冒号
得到一个数组:array('01' => '富裕', '02' => '一般')
剩下就好办了
------解决思路----------------------

本帖最后由 xuzuning 于 2015-04-26 17:27:34 编辑
$a1 = '02';<br />$a2 = '01';<br />$a3 = '03';<br /><br />$c1 = '01';<br />$c2 = '03';<br />$c3 = '05';<br /><br />$na = 'a';<br />parse_str(str_replace(array(':', PHP_EOL), array('=', '&'), file_get_contents("data/$na.txt")), $ar);<br />foreach(preg_grep("/^$na\d+/", array_keys(get_defined_vars())) as $v) {<br />  $$v = $ar[$$v];<br />}<br />$na = 'c';<br />parse_str(str_replace(array(':', PHP_EOL), array('=', '&'), file_get_contents("data/$na.txt")), $ar);<br />foreach(preg_grep("/^$na\d+/", array_keys(get_defined_vars())) as $v) {<br />  $$v = $ar[$$v];<br />}<br />echo $a1, PHP_EOL;<br />echo $a2, PHP_EOL;<br />echo $a3, PHP_EOL;<br />echo $c1, PHP_EOL;<br />echo $c2, PHP_EOL;<br />echo $c3, PHP_EOL;<br />
Copy after login
一般
富裕
贫穷
中国
德国
葡萄牙

你的方案就是错的,不可能获得良好的性能
Related labels:
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