我在这里进行了广泛搜索,但没有解决我的问题的方法(php)。
场景:用户使用预先分配的注册号码(在datafile.txt中)访问登录页面,在该字段中输入该号码时,脚本将搜索文件(如果存在)。
如果存在,请继续下一步。下一步完成后,我希望它一旦完成就自动“删除”原来使用的号码。
我相信在寻找“完全匹配”的同时,“搜索并替换”是必经之路。
我的数据文件类似于以下内容:(datafile.txt)
0
12
123
1234
12345
123456
12,如果搜索,则与123不同。
我几天前得到的一个脚本很好地完成了另一个任务:
$numbers = file_get_contents("datafile.txt");
$uNumber = $_POST['uNum'];
if ( @preg_match( "/([^0-9]{$uNumber}[^0-9])/", $numbers ) ) {
echo "Numbers match";
}
我尝试完成一项新任务的方法如下,但没有成功:
$numbers = file_get_contents('datafile.txt', 'w+');
$uNumber = $_POST['uNum'];
if ( @preg_match( "/([^0-9]{$uNumber}[^0-9])/", $numbers ) ) {
$numbers = preg_replace('.$_Post["uNum"]','',$numbers);
echo "Existed but will be deleted from file. ";
} else {
echo "Message showed if not in file.";
}
任何帮助将不胜感激。
最佳答案
这个怎么样:
$index = file_get_contents("datafile.txt");
$bodycont = str_replace("string to be replaced","what you want that string to be",$index);
$fh = fopen("datafile.txt","w");
fwrite($fh,$bodycont);
fclose($fh);
要么:
$file = file("datafile.txt", FILE_IGNORE_NEW_LINES);
foreach($file as $text) {
$test[] = $text;
}
//get the size of the array
$arraysize = sizeof($test);
//use for loop to check if that string is found in the array and replace it
for($x=0;$x<$arraysize;$x++)
{
if($test[$x] == "$uNumber")
{
}
else
{
$newarray[] = $test[$x];
}
}
$stringData = implode("\n",$newarray );
$fh = fopen("datafile.txt","w");
fwrite($fh,$stringData );
fclose($fh);
这应该以某种方式工作。 :D