【问题标题】:Converting a txt file to string, then to array and then printing each word of the array将 txt 文件转换为字符串,然后转换为数组,然后打印数组的每个单词
【发布时间】:2016-11-14 15:16:29
【问题描述】:

我正在尝试将文本文件转换为字符串,然后转换为数组,最后将每个值(单词)打印到单独的“a”持有者中。

.txt 文件包含一行文本。

我已经通过 for 循环尝试过,如下所示:

    $lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
    $words = explode(" ", $lines);

    for ($x = 1; $x >= 100; $x++){
        print '<a id="word$x">'$words[$x]'</a>';
    }

但这不起作用。我确信我只是缺少一些基本的东西,但我已经尝试过很多次但都失败了,我需要其他人的意见和建议。

【问题讨论】:

    标签: php html arrays string text


    【解决方案1】:

    首先,不要忘记字符串连接:print '&lt;a id="word'.$x.'"&gt;'.$words[$x].'&lt;/a&gt;';

    如果你需要更多,而不是只有 100 个字,请在你的 for 中使用 $x &lt; count($words)

    【讨论】:

    • 完美运行!我会检查这个答案是否正确。 ps:谢谢
    【解决方案2】:

    你必须使用 =

    for ($x = 1; $x <= 100; $x++){
        print '<a id="word$x">'$words[$x]'</a>';
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用sprinf,它更容易阅读。

      $lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
      $words = explode(" ", $lines);
      
      for ($x = 1; $x >= 100; $x++){
        echo sprintf('<a id="word%s">%s</a>', $word, $words[$x]);
      }
      

      但如果您不想这样做,您可以简单地连接这些值。

      echo '<a id="word' . $x . '">' . $words[$x] . '</a>';
      

      【讨论】:

        【解决方案4】:

        使用显式 for 循环是一种不好的做法。

        $lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
        $words = explode(" ", $lines);
        $words = array_slice($words, 0, 100);
        
        foreach ($words as $index => $word) {
            print "<a id=\"word$x\">$word</a>";
        }
        

        另外,注意数组索引以0 开头,而不是1。如果你这样做$x = 1,你最终会失去第一个字!

        如果您想打印所有单词,只需丢失$words = array_slice($words, 0, 100);。阅读更多关于array_slicehere的信息。

        【讨论】:

        • 是的,我忘记了数组将第一个值设为 0,从前端开发到 php 在此过程中会产生一些困难...谢谢您
        猜你喜欢
        • 2017-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-06
        • 2019-10-16
        相关资源
        最近更新 更多