Rumah > pembangunan bahagian belakang > tutorial php > PHP基础示例:用正则表达式修改配置信息

PHP基础示例:用正则表达式修改配置信息

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Lepaskan: 2016-08-08 09:23:24
asal
1058 orang telah melayarinya

各php工作原理图:

以下是扯代码时间:

1

2

<span>php

</span><span>//</span><span>配置文件信息</span><span>define</span>("HOST","localhost"); <span>//</span><span>主机名</span><span>define</span>("USER","rootaaaa");      <span>//</span><span>用户名</span><span>define</span>("PASSWORD","root123456");  <span>//</span><span>密码</span><span>define</span>("DBNAME","mydb");    <span>//</span><span>数据库名</span>

Salin selepas log masuk
dbconfig.php

1

2

3

4

5

6

7

8

9

10

11

12

13

<span>php

 

</span><span>//</span><span>执行配置文件的修改操作

 

//1.读取配置文件的信息</span><span>$info</span> = <span>file_get_contents</span>("dbconfig.php"<span>);

</span><span>//</span><span>2.对POST遍历,并对配置文件信息进行正则替换</span><span>foreach</span>(<span>$_POST</span><span>as</span><span>$k</span> => <span>$v</span><span>)

{

    </span><span>$info</span>=<span>preg_replace</span>("/define\(\"{<span>$k</span>}\",\"(.*?)\"\)/","define(\"{<span>$k</span>}\",\"{<span>$v</span>}\")",<span>$info</span><span>);

}

</span><span>//</span><span>3.将替换后的信息写回到配置文件中</span><span>file_put_contents</span>("dbconfig.php",<span>$info</span><span>);

 

</span><span>echo</span> "<h2>修改成功!</h2>"<span>;

</span><span>echo</span> "<a href="edit.php">返回</a>";

Salin selepas log masuk
doupdate.php

1

2

3

4

5

6

7

8

<span>php

 

</span><span>//</span><span>编辑配置文件</span><span>$keyinfo</span>=<span>array</span>("HOST"=>"主机","USER"=>"用户","PASSWORD"=>"密码","DBNAME"=>"数据库名"<span>);

 

</span><span>//</span><span>1.读取配置文件的信息</span><span>$info</span> = <span>file_get_contents</span>("dbconfig.php");<span>//</span><span>将dbconfig.php文件中信息读出并赋值给info变量

//2.使用正则表达式解析配置文件的信息</span><span>preg_match_all</span>("/define\(\"(.*?)\",\"(.*?)\"\)/",<span>$info</span>,<span>$a</span>);<span>//</span><span>将info中的信息解析到a变量中存储

//3.遍历解析后的信息,并输出到修改表单中</span><span>echo</span> "<h2>编辑配置文件</h2>"<span>;

</span><span>echo</span> "

Salin selepas log masuk
"; foreach($a[1] as$k =>$v) { echo "{$keyinfo[$v]}:

"; } echo " "; echo ""; echo "
";edit.php

以上就介绍了PHP基础示例:用正则表达式修改配置信息,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan