PHP修改TXT文件

我有一个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);
?>

有人可以帮助我填补空白吗?

解决方法

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

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

相关参考文献:

> http://php.net/manual/en/function.explode.php
> http://www.php.net/manual/en/function.array-shift.php
> http://php.net/manual/en/function.current.php
> http://php.net/manual/en/function.file-put-contents.php

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...