0

remove txt file line by line using php? have txt file like this

.../path/ffdfygfftg_230x260.jpeg
.../path/ttttoooooop_125x340.png
.../path/pppppppffd_450x440.gif

i have 70.000 line link image for this.. but this tumbnail size...

normal size link is

.../path/ggdfghfdf.jpeg

So I am looking for a way to open the text file, reading it line by line and removing start from (_) values while also removing end before dot (.)

posible using php?

vallez
  • 117
  • 1
  • 1
  • 10

2 Answers2

0

This will remove everything between the last underscore .

$filename = '.../path/ffdfygfftg_230x260.jpeg';
$new_filename = preg_replace('/_[^_.]*\./', '.', $filename);
echo $new_filename;

Output

.../path/ffdfygfftg.jpeg
Drudge Rajen
  • 7,584
  • 4
  • 23
  • 43
0

Depending on how much memory usage matters, the following snippet is a simple way to alter every line in the text file. The downside of this method is that the entire text file will be loaded in memory before it is altered.

    $filecontents = file_get_contents('/path/to/file.txt'); //Load the file contents
    $newcontent = preg_replace('/(_)(.*)(\.)(.*)/' '.${4}', $filecontents); //Use a regular expression to alter the file contents. The replacement (.${4}) adds the . and the file extension back into the line.
    file_put_contents('/path/to/file.txt', $newcontent);

To make it more memory efficient, look into the fgets() function, and apply it with the same regular expression

Kontsnor
  • 146
  • 4
  • what is the function of (.${4}) ? – vallez Feb 05 '16 at 07:55
  • Did you read the comment on the line where it is used? It's explained there. The . is just a dot. The ${4} is the 4th match in the regular expression (so the file extension). Thus this adds . back into the line. – Kontsnor Feb 05 '16 at 07:58
  • for all file extention , like .png, jpg, gif , jpeg, etc ? – vallez Feb 05 '16 at 08:07
  • It doesn't matter, even it was an extension like .asdf, this is a general solution, if your path contains just 1 underscore. – Kontsnor Feb 05 '16 at 08:26
  • whether it function ${4} will calculate the letter of jpeg (4 char) ? , if true ,how about png (3 char) or gif ? – vallez Feb 05 '16 at 08:57
  • No, that's false. The trick is in the '/(_)(.*)(\.)(.*)/' part. There are 4 sets of brackets. The last bracket (.*) matches everything after the dot (this is the file extension). Next, the ${4} references the last bracket (.*), which is the file extension. So wheter it is 2, 3, or 30 characters long, it doesn't matter. – Kontsnor Feb 05 '16 at 09:04
  • i try it but error .. Parse error: syntax error, unexpected ''.${4}'' (T_CONSTANT_ENCAPSED_STRING) in /home/path/public_html/path/apps/replc/rep.php on line 4 – vallez Feb 05 '16 at 10:11