0

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

Radish H.
  • 62
  • 1
  • 8
  • Hello, what do you mean by "a sentences" ? do you mean "lines" ? if yes then let me know if you want to replace one single line by your code or all lines? – sohaieb azaiez May 25 '19 at 15:54
  • I mean just a sentence ("I love Mary", "She doesn't love me", ecc.), in a line can be a lot of sentences or code. – nino_user183677 May 25 '19 at 16:24
  • do you mean that you want to replace for example : `12345Temple 12345Temple 12345Temple 99999Cheope` by this ? : `12345 12345 12345 99999` ? – sohaieb azaiez May 25 '19 at 16:30
  • I want replace every occurence of "Cheope" by "9999" and of "Temple of Cheope" by "12345". With my code I get "99999" and "Temple of 99999"! and I have to use PHP – nino_user183677 May 26 '19 at 06:00

1 Answers1

1

according to what you said and what I understand from you , this is what you need:

set_time_limit( 0 );
//  Initialization
$inputfile           = "sentences.txt";
$outputFile          = 'longfile.php';
$matches             = array();
$extractedNumbers    = array();
$numberOfLines       = count( file( $inputfile ) );
$numberOfReadedLines = 1; // this will be used to check if the counter is on the last line or not;
//  Implementation
$GetCodice  = @fopen( $inputfile, "r" );
$newfile    = @fopen( $outputFile, 'w+' );
if ( $GetCodice ) {
    while ( ( $line = fgets( $GetCodice ) ) !== false ) {
        preg_match( '/^[0-9]+/m', $line, $matches );
        array_push( $extractedNumbers, $matches[0] );
        $position = sizeof( $extractedNumbers ) - 1;
        if ( $numberOfReadedLines == $numberOfLines ) { // if the counter is in the last line then we don't need to write a new empty line with the "\r"
            $newOutputLine = $extractedNumbers[ $position ];
        } else {
            $newOutputLine = $extractedNumbers[ $position ] . "\r";
        }
        fwrite( $newfile, $newOutputLine );
        $numberOfReadedLines++;
        //replace_file($file, $msg, $codice);

    }
    fclose( $newfile );
    fclose( $GetCodice );

}

(if this is not what you need so feel free to comment, we can find an ameliorations, i just need more examples to understand your need more)

sohaieb azaiez
  • 768
  • 9
  • 20
  • Thank you very much. Unfortunately it does not work. I do not understand where the sentence from the inputfile (sentences.txt) are searched and replaced in the lines of the outputfile (longfile.php). I get an error at line: array_push( $extractedNumbers, $matches[0] ); – nino_user183677 May 26 '19 at 14:57
  • you are welcome, for me it works like a charm, so can you past the error message here please? to explain what I did:the sentence of the input file are searched by each line in your file using the "preg_match" function (it is a regular expression function).. I used it to extract numbers from your current and put it in the **$matches** array than it append it to the output file – sohaieb azaiez May 26 '19 at 15:29
  • Hi, this is the error message: Notice: Undefined offset: 0 in ....\trovasost2.php on line 16 (i.e. array_push( $extractedNumbers, $matches[0] ); and the longfile is empty! – nino_user183677 May 27 '19 at 16:15
  • you did not specify if your input file can contain sentenses without code ? the error indicates that there is a line (probably line 16) does not contain a code, but it contains only letters – sohaieb azaiez May 27 '19 at 21:44