【发布时间】:2017-08-01 09:58:32
【问题描述】:
我有一个具有以下设计的文本文件:
约翰·史密斯|1|john@smith.com|nopassword|admin
汤姆·史密斯|3|tom@smith.com|admin123|用户
....
等等。 每个字段都由“|”分隔。 我需要做的是替换值,例如此文本文件中用户的密码或帐户类型。
汤姆·史密斯|5|tom@smith.com|admin1234|admin
我成功找到了该行并使用explode() 将其吐出,但是如何修改该值并将其写回到文本文件中?
$name = $_POST['name'];
$mydb = file('./DB/users.txt');
foreach($mydb as $line) {
if(stristr($line,$name)) $pieces = explode("|", $line);
$position = str_replace(array("\r\n","\r"),"",$pieces[1]);
$email = str_replace(array("\r\n","\r"),"",$pieces[2]);
$password = str_replace(array("\r\n","\r"),"",$pieces[3]);
$atype = str_replace(array("\r\n","\r"),"",$pieces[4]);
【问题讨论】:
-
你能把你现有的代码放在这里吗?
-
您是要全部修改,还是只修改一个?
-
另外,您是否考虑过使用数据库?这看起来更像是数据库的工作。
-
$name = $_POST['name']; $mydb = file('./DB/users.txt'); foreach($mydb as $line) { if(stristr($line,$name)) $pieces = explode("|", $line); $position = str_replace(array("\r\n","\r"),"",$pieces[1]); $email = str_replace(array("\r\n","\r"),"",$pieces[2]); $password = str_replace(array("\r\n","\r"),"",$pieces[3]); $atype = str_replace(array("\r\n","\r"),"",$pieces[4]); }
-
一个数据库没关系,但这更容易使应用程序在工作中具有可移植性。
标签: php string file text replace