I would like to replace sentences by a code in a large file. I've tried to use str_replace, but because in the file there some of the same words of the sentence, my code replaces them and doesn't recognize the sentence!
<?php
// sentences,txt
// 12345Temple of Cheope
// ..........
// 99999Cheope
set_time_limit(0);
$GetCodice=@fopen("sentences.txt", "r");
if ($GetCodice) {
while(!feof($GetCodice)) {
$StoreCodice=fgets($GetCodice,4096);
$codice='".'.substr($StoreCodice, 0, 6).'."'; // abcd
$msg=trim(substr($StoreCodice, 6)); // abcd
echo $msg."<br>";
$n=0;
$file = 'longfile.php';
replace_file($file, $msg, $codice);
}
fclose($GetCodice);
}
// From https://stackoverflow.com/questions/2159059/string-replace-in-a-large-file-with-php
function replace_file($path,$string, $replace)
{
set_time_limit(0);
if (is_file($path) === true)
{
$file = fopen($path, 'r');
$temp = tempnam('./', 'tmp');
if (is_resource($file) === true)
{
while (feof($file) === false)
{
file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
}
fclose($file);
}
unlink($path);
}
echo $replace."<BR>";
return rename($temp, $path);
}
?>
The sentences are ordered according to their descending length. I thought that this order would avoid replacing a shorter sentence or word in a longer sentence. I expect the output
12345
.....
99999
but the actual output is
Temple of 9999
.....
99999
Can I get some help?
Thank you in advance