Home >Backend Development >PHP Tutorial >Classes for text manipulation in php_PHP tutorial
Let me give you a simple text operation class
I wrote it before, but I never had the chance to use it. Text is not as good as a database
Data is saved in rows and ends with n. Please note that the data you enter must end with " n", these are the most basic class members. For text, special attention should be paid to efficiency issues. For example, if you want to update lines 2, 3, and 4 of the file, use:
for($i=2;$i< ;=4;$i++)$this->update($file,$i,$msg);Not as good as this:
$data=$this->read($file);
for( $i=2;$i<=4;$i++)$data[$i]=$msg;
$this->write($file,$data); of
class text{
var $key=""; //Data protection
var $keylen; //Data protection length
function text() //Class construction Device
{
$this->keylen=strlen($this->lkeylen); //Get the protected length
}
function read($file) //Read the file and return a Array
{
if(file_exists($file)):
$data=@file($file);
$data[0]=substr($data[0],$this- >keylen);
return $a;
endif;
}
function write($file,$data=array()) //Write the file, the data is an array
{
if($fp=fopen($file,"w")):
flock($fp,3);
fwrite($fp,$this->key);
foeach ($data as $v)fwrite($fp,$v);
return true;
endif;
}
function add($file,$msg)
//Add to file Finally add the data (create the file first if it does not exist)
{
$a=$this->read($file); //This does not matter whether the file exists or not
$a[]=$msg;
return $this->write($file,$a);
}
function insert($file,$n,$msg) //Insert data before $nth
{
if($a=$this->read($file)):
$a[$n]=$msg.$a[$n];
return true;
endif ;
}
function updata($file,$n,$msg) //Update $n data
{
if($a=$this->read($file)):
$a[$n]=$msg;
return true;
endif
}
function del($file,$n) //Delete $n data
{
return $this->updata($file,$n,"");
}
}