首頁 >後端開發 >php教程 >PHP基礎範例:用正規表示式修改設定資訊

PHP基礎範例:用正規表示式修改設定資訊

WBOY
WBOY原創
2016-08-08 09:23:241028瀏覽

各php運作原理圖:

以下是扯碼時間:

<?<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>

dbconfig.php

<?<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>";
dbconfig.php

<?<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> "<form action='doupdate.php' method='post'>"<span>;

</span><span>foreach</span>(<span>$a</span>[1] <span>as</span><span>$k</span> =><span>$v</span><span>)
{
    </span><span>echo</span> "{<span>$keyinfo</span>[<span>$v</span>]}:<input type='text' name='{<span>$v</span>}' value='{<span>$a</span>[2][<span>$k</span>]}' /><br/><br/>"<span>;
}

</span><span>echo</span> "<input type='submit' value='编辑' />&nbsp"<span>;
</span><span>echo</span> "<input type='reset' value='重置' />"<span>;
</span><span>echo</span> "</form>";
dbconfig.php
rrreee

dbconfig.phprrreee

dbconfig.php

🎜rrreee🎜🎜dbconfig.php🎜 🎜🎜🎜🎜rrreee🎜🎜 edit.php🎜🎜 🎜 以上就介紹了PHP基礎範例:用正規表示式修改配置訊息,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。 🎜 🎜 🎜
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn