简体   繁体   中英

PHP modify TXT file

I have a ID.txt file that looks like this:

"http://something.net/something-ak/41389_718783565_1214898307_q.jpg"
"http://something.net/something-ak/372142_106502518141813_1189943482_q.jpg"
and so on

I want to use PHP to open the file and remove everything before the first " _ " and everything after the second " _ " so I wind up with this:

718783565
106502518141813
and so on

Thing is I don't really know how to do that.

This is what I have so far:

<?PHP
$file_handle = fopen("ID.txt", "rb");

while (!feof($file_handle) ) {

$line_of_text = fgets($file_handle);
$parts = explode('\n', $line_of_text);

// Remove everything before the first "_" and everything after the last "_".
// echo the line
}

fclose($file_handle);
?>

Can someone help me fille in the blanks?

This is what I would do, although a regex might be shorter or more efficient:

$file_handle = fopen("ID.txt", "rb");
while (!feof($file_handle) )
{
    $line_of_text = fgets($file_handle);
    $parts = explode("\n", $line_of_text);

    foreach ($parts as $str)
    {
        $str_parts = explode('_', $str); // Split string by _ into an array
        array_shift($str_parts); // Remove first element
        echo current($str_parts)."\n"; // echo current element and newline
        // Same as $str_parts[0]
    }
}
fclose($file_handle);

Demo: http://codepad.org/uFbVDtbR

Not a big deal, but $lines might be a better variable name there instead of $parts .

If you do need to write this back to the file, you can do this:

ob_start();
// code used above
$new_content = ob_get_clean();
file_put_contents("ID.txt", $new_content);

Relevant references:

Just use file in a loop

$content = "";
foreach(file("ID.txt", FILE_SKIP_EMPTY_LINES) as $line){
    $parts = explode('_', $line);
    $content .=  $parts[1] . "\n";
}
file_put_contents("ID.txt", $content);

If you want to achieve this by ,

awk -F _ '{print $2}' ID.txt
$TXT = file_get_contents(__DIR__.'/in.txt');
$NewTXT = preg_replace('~^.+/[0-9]+_([0-9]+)_.+?$~mi', '$1', $TXT);
file_put_contents(__DIR__.'/out.txt', $NewTXT);

Just rename the .txt files accordingly.

Try this

preg_match('/(.*? )(.+?)( .*)/',$line,$matches);

$matches[2] will give the required string

This should work

<?php
// open files
$file_handle = fopen("ID.txt", "rb");
$new_file_handle = fopen("ID2.txt", "wb");

while (!feof($file_handle) ) {
  $str = fgets($file_handle);
  $start = strpos($str, '_'); // find first "_"
  $end = strpos($str, '_', $start + 1); // find next "_"
  $newstr = substr($str, $start + 1, $end - $start - 1) . "\n";
  fputs($new_file_handle, $newstr);
}
// close files
fclose($file_handle); 
fclose($new_file_handle);
// rename
rename("ID2.txt", "ID.txt");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM