PHP根据文件中的文本替换文本
问题描述:
i have textfile.txt:
aaa
bbb
...
zzz
i want remove some text based on text from textfile.txt
ex: we have aaa files ==> we have files
my codes still not work :
<?php
$fp = @fopen("textFile.txt", 'r');
$array = explode("
", fread($fp, filesize("textFile.txt")));
if (isset($_POST['btcari'])){
print_r(str_ireplace($array,"", $_POST['tateks']));
}
?>
thanks vo ur appreciate
答
Try this:
$array = file("textFile.txt");
function _trim( &$value, $key ) {
$value = trim( $value );
}
// remove the newlines and extra spacing
array_walk( $array, '_trim' );
$replaceArray = array_fill( 0, count($array), '' );
if( isset( $_POST[ 'btcari' ] ) ) {
echo str_replace( $array, $replaceArray, $_POST[ 'tateks' ] );
}
Hope it helps.
答
First read the file and change text inside it. Then write into file the new content.
$fp = @fopen("textFile.txt", 'r');
$array = explode("
", fread($fp, filesize("textFile.txt")));
fclose($fp);
foreach($array as $text) {
$textall .= str_replace("aaa", "", $text);
}
$fh = fopen("textFile.txt", "w") or die("Could not open log file.");
fwrite($fh, $textall) or die("Could not write file!");
fclose($fh);
答
You can use preg_replace
$replace = "/".$_POST['tateks']."/";
$array = preg_replace($replace , '' , $array);
print_r($array);
答
You seem to be using wrong post parameter for replace. I tried the code and if you use $_POST[btcari'] instead of $_POST['tateks'], it works fine.
<?php
$fp = @fopen("textFile.txt", 'r');
$array = explode("
", fread($fp, filesize("textFile.txt")));
if (isset($_POST['btcari'])){
print_r(str_ireplace($array,"", $_POST['btcari']));
}
?>
Now if i send a post parameter named "btcari", it outputs the replaced text correctly.