为什么strlen计算长度比实际长度高两个?

时间:2013-02-16 22:29:38

标签: php

我有以下代码:

<?php
if (!isset($_SESSION["word"])) {
    $dictionary_file = new SplFileObject("dictionary.txt");
    $dictionary_file->seek(rand(0, 80367));
    $_SESSION["word"] = $dictionary_file->current();
    $_SESSION["word_progress"] = "";

    for ($i = 0; $i < strlen($_SESSION["word"]); $i++) {
        $_SESSION["word_progress"] .= "_";
    }
    echo strlen($_SESSION["word"]);
    echo $_SESSION["word"];
}
else {
    if (isset($_GET["guess"])) {
        // If their guessed letter is in the word
        if (stripos($_SESSION["word"], $_GET["guess"]) !== false) {
            $occurrence_points = strposall($_SESSION["word"], $_GET["guess"]);
            $progress = $_SESSION["word_progress"];

            foreach ($occurrence_points as $values) {
                $progress[$values] = $_GET["guess"];
            }

            $_SESSION["word_progress"] = $progress;
        }
    }
}

?>

我从文件中随机生成一个单词。说它产生“泡沫”。长度是6,但它会报告8,即使在打印出来之后确认这个词确实是泡沫。这是为什么?

1 个答案:

答案 0 :(得分:1)

随机生成的单词可能正在添加空格。做一个trim()

   $_SESSION["word"] = trim($dictionary_file->current());