开发者

PHP File Operation

开发者 https://www.devze.com 2023-03-16 11:57 出处:网络
I am trying t开发者_运维技巧o create a text file with PHP in fopen(\"test.txt\",\"a\"). I have also tried with fopen(\"test.txt\",\"w+\").

I am trying t开发者_运维技巧o create a text file with PHP in fopen("test.txt","a"). I have also tried with fopen("test.txt","w+").

The text file is created but I want to check for some string in test.text, that it exist or in test.txt it will not create duplicate entry. Can someone help me out?


Use this code:

$content = file_get_contents('test.txt');
if (str_pos('YOUR KEYWORD', $content) !== false){
// your keyword exists in the file
}


if (!file_exists("test.txt"))
{
    ///file does not exist
}
else
{
    $f = fopen("test.txt", "a"); 
    fwrite($f, "appending text");
}

searching in file:

$arr = file_get_contents("test.txt");
if (preg_match("/your_rexexp/i", $arr))
{
     echo "text found";
}


If I understand you correctly, you want to insert new values into a textfile, but first check if the value already exists in it.

You can use fread() to get the contents of the file, and then through preg_match() you can check for values in the file.


If you are using PHP5 then you can use some of the new easy functions.

file_exists(filename) returns boolean sayin if the file exists. file_put_contents(filename,data) returns boolean saying if the write was successful. file_get_contents(filename) returns the contents of the file (string).

0

精彩评论

暂无评论...
验证码 换一张
取 消