【问题标题】:PHP read each linePHP读取每一行
【发布时间】:2010-09-01 15:12:18
【问题描述】:

我有一个<textfield> ($_POST['list'])。

如何将每行的值获取到数组键中?

例子:

<textfield name="list">Burnett River: named by James Burnett, explorer
Campaspe River: named for Campaspe, a mistress of Alexander the Great
Cooper Creek: named for Charles Cooper, Chief Justice of South Australia 1856-1861
Daintree River: named for Richard Daintree, geologist
</textfield>

应转换为:

Array(
[Burnett River: named by James Burnett, explorer]
[Campaspe River: named for Campaspe, a mistress of Alexander the Great]
[Cooper Creek: named for Charles Cooper, Chief Justice of South Australia 1856-1861]
[Daintree River: named for Richard Daintree, geologist]
)

谢谢。

【问题讨论】:

    标签: php arrays post textarea


    【解决方案1】:

    使用explode 函数,然后修剪结果数组(以去除任何剩余的\n\r 或任何意外的空格/制表符):

    $lines = explode("\n", $_POST['list']);
    $lines = array_map('trim', $lines);
    

    【讨论】:

      【解决方案2】:

      这是最安全的方法。它并不假定您可以丢弃回车 (\r) 字符。

      $list_string = $_POST['list'];
      
      // \n is used by Unix. Let's convert all the others to this format
      
      // \r\n is used by Windows
      $list_string = str_replace("\r\n", "\n", $list_string);
      
      // \r is used by Apple II family, Mac OS up to version 9 and OS-9
      $list_string = str_replace("\r", "\n", $list_string);
      
      // Now all carriage returns are gone and every newline is \n format
      // Explode the string on the \n character.
      $list = explode("\n", $list_string);
      

      Wikipedia: Newline

      【讨论】:

        【解决方案3】:

        您可以使用explode() 并在换行符\n 处爆炸。

        $array = explode("\n", $_POST['list']);
        

        【讨论】:

        • 对于谁反对我们,请在评论中详细说明。谢谢!鉴于蒂姆的回答,我会假设是他。简单地说,以上“大部分”时间确实有效。您详细说明了一些情况,它不起作用。这是否值得一票否决,即使它确实解决了答案,至少大多数时间?
        • 大部分时间是回车。
        • 好吧,我明白了。但是,即使使用回车,上述方法仍然有效。并且回车很少会影响应用程序,而不是作为剩余字符。关键是,这确实解决了问题,即使它可能不是“最佳”路线。
        • 我将这个问题解释为询问如何通过换行符将输入字符串拆分为数组,以便每个元素的第一个和最后一个字符都是可打印的。如果此数据保存在任何地方(数据库或文件),无关字符很可能会影响其完整性。
        • 是的,我可以看到。要么,要么,它“应该”工作,但我同意要么像 aularon 那样修剪,要么进行更换。不过,我会选择array_maptrim,作为我的偏好。
        【解决方案4】:

        explode("\n", $_POST['list'])

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多