PHP修改TXT文件

时间:2012-03-30 05:29:59

标签: php file parsing

我有一个ID.txt文件,如下所示:

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

我想使用PHP打开文件并删除第一个“_”之前的所有内容以及第二个“_”之后的所有内容,所以我结束了这个:

718783565
106502518141813
and so on

我真的不知道该怎么做。

这是我到目前为止所做的:

<?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);
?>

有人可以帮我填空吗?

5 个答案:

答案 0 :(得分:2)

这就是我要做的,虽然正则表达式可能更短或更有效:

$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);

演示:http://codepad.org/uFbVDtbR

没什么大不了的,但$lines可能是更好的变量名,而不是$parts

如果您确实需要将此内容写回文件,则可以执行以下操作:

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

相关参考文献:

答案 1 :(得分:2)

只需在循环中使用file

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

如果您想通过实现此目的,

awk -F _ '{print $2}' ID.txt

答案 2 :(得分:0)

试试这个

的preg_match(&#39; /(* )(+)( *)/&#39;??,$线,$匹配);

$ matches [2]将提供所需的字符串

答案 3 :(得分:0)

这应该有效

<?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");

答案 4 :(得分:0)

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

只需相应地重命名.txt文件。

相关问题