我有一个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
事情是我真的不知道该怎么做.
这是我到目前为止:
$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);
没什么大不了的,但$lines可能是一个更好的变量名,而不是$parts.
如果确实需要将其写回文件,则可以执行以下操作:
ob_start();
// code used above
$new_content = ob_get_clean();
file_put_contents("ID.txt", $new_content);
相关参考文献:
标签:php,file,parsing
来源: https://codeday.me/bug/20190626/1291258.html