我有一个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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。