加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP修改TXT文件

发布时间:2020-12-13 17:11:26 所属栏目:PHP教程 来源:网络整理
导读:我有一个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打开文件并删除第一个“_”之前的所有内容以及第
我有一个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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读