读取文件并使用分隔符进行拆分


Read a file and split with delimiter

我有这个文本文件

acmst501:57:Runningacmst506:201:Runningacmst506:203:Runningacmst506:209:Runningacmst506:213:Failed

我想用分隔符分隔。我有这个代码工作。

    <?php
function parseFile($filename, $delimiter) {
    global $splitcontents;
    //$fd = fopen ($filename, "r");
    //$contents = fread ($fd,filesize ($filename));
    //fclose ($fd);
    $contents = file_get_contents($filename);
    $splitcontents = explode($delimiter, $contents);
    return $splitcontents;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Read file and split with delimiter</title>
</head>
<body>
<?php
    parseFile("c:'emap'asrvr505-cslot_state.txt",":");
    foreach ( $splitcontents as $value ) {
        echo "<b>$value<br>";
    }
?>
</body>
</html>

我得到的输出是:

acmst501
57
Running acmst506
201
Running acmst506
203
Running acmst506
209
Running acmst506
213
Failed

然而,我希望它是这样的:

acmst501
57
Running
acmst506
201
Running
...

因此,基本上,我想将运行/失败部分从acst字段中分离出来。

我该如何分离这些?另外,我的函数是否正确,这样我就可以在同一个PHP文件中的不同文件中使用它?谢谢

这:

$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));
fclose ($fd);

将整个缓冲区一次放入$contents中-如果这是您的目标,您还可以使用file_get_contents()

在您的输入中,您有:Runningacmst506。那里没有分隔符。我假设您在:上进行拆分,但Running附近没有冒号。

你的示例输入中有错别字吗?

如果你澄清你的意见,我可以给你一个更好的答案。