我的PHP定义的字符串正在被扰乱。为什么?

时间:2014-01-30 16:50:43

标签: php string

我有这段代码。

$archivePath = 'archive/archive.txt';
$archiveReader = fopen($archivePath, 'r');
$numberOfStatements = 0;
while (!feof($archiveReader)) {
    $thisLine = fgets($archiveReader);
    list($identifier, $state, $day, $month, $year, $tags) = explode('|', $thisLine);
    $tags = explode(',', $tags);
    $lineToEcho = "statement #" . $identifier . " is " . $state . ". Date:" . $day . "." . $month . "." . $year . " tags: ";
    $numberOfTags = count($tags);

    for ($k = 0; $k < $numberOfTags; $k++) {
        if ($k != 0) {
            $lineToEcho .= $tags[$k] . ", ";
        } 
        $lineToEcho .= $tags[$k];
    }
    $lineToEcho .= "<br>";
    echo $lineToEcho;
    $numberOfStatements++;
}
fclose($archiveReader);

代码应该以这种格式返回字符串

statement #0 is raw. Date:30.01.14 tags: war,piece 

但是以这种格式返回:

statement #0 is raw. Date:30 01 14.war,piece . tags: 

为什么我的字符串会重新格式化,如何阻止它发生?

编辑:archive.txt看起来像这样:

0|raw|30 01 14|war,piece
1|raw|30 01 14|drugs,abstinence

EDIT2:在FireFox中查看源代码时,我看到了:

statement #0 is raw. Date:30 01 14.war,piece
. tags: <br>statement #1 is raw. Date:30 01 14.drugs,abstinence
. tags: <br>//next entry

2 个答案:

答案 0 :(得分:2)

这条线看起来很糟糕:

$lineToEcho = $tags[$k] . ", ";

应该是:

$lineToEcho .= $tags[$k] . ", ";
//          ^-- . here

$a .= "b"; // is equivalent to
$a = $a . "b";

答案 1 :(得分:0)

为lineToEcho添加值的第一行工作正常。问题是,它将在你的for循环中被覆盖:

$lineToEcho = "statement #" . $identifier . " is " . $state . ". Date:" . $day . "." . $month . "." . $year . " tags: ";

在你的for循环中,你根本不想使用这些点,你只需要用逗号分隔你的标签。

for ($k = 0; $k < $numberOfTags; $k++) {
    if ($k != 0) {
        $lineToEcho = $tags[$k] . ", ";
    } 
    $lineToEcho = $lineToEcho . $tags[$k];
}

因此,如果你想保留上面的那一行和你的循环中的那一行,删除重置$ lineToEcho的if子句。