【问题标题】:Converting content of text area into an array将文本区域的内容转换为数组
【发布时间】:2009-09-09 08:37:46
【问题描述】:

我有一个带有 html 文本区域的表单。 我想在php中获取这个文本区域的内容,以便每一行都可以存储在一个数组中。我尝试使用带有'/n'的内爆。但它不工作。我该怎么做。

这是我的代码

$notes = explode('/n',$_POST['notes']);   

【问题讨论】:

    标签: php html textarea


    【解决方案1】:

    你需要使用这个:

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

    (反斜杠,不是正斜杠,用双引号代替单引号)

    【讨论】:

      【解决方案2】:

      Palantir 的解决方案只有在行以 \n 结尾(Linux 默认行结尾)时才有效。

      例如。

      $text     = "A\r\nB\r\nC\nD\rE\r\nF";    
      $splitted = explode( "\n", $text );
      
      var_dump( $splitted );
      

      将输出:

      array(5) {
        [0]=>
        string(2) "A "
        [1]=>
        string(2) "B "
        [2]=>
        string(1) "C"
        [3]=>
        string(4) "D E "
        [4]=>
        string(1) "F"
      }
      

      如果没有,你应该使用这个:

      $text     = "A\r\nB\r\nC\nD\rE\r\nF";
      $splitted = preg_split( '/\r\n|\r|\n/', $text );
      var_dump( $splitted );
      

      或者这个:

      $text     = "A\r\nB\r\nC\nD\rE\r\nF";
      $text     = str_replace( "\r", "\n", str_replace( "\r\n", "\n", $text ) );
      $splitted = explode( "\n", $text );
      var_dump( $splitted );
      

      我认为最后一个会更快,因为它不使用正则表达式。

      例如。

      $notes = str_replace(
          "\r",
          "\n",
          str_replace( "\r\n", "\n", $_POST[ 'notes' ] )
      );
      
      $notes = explode( "\n", $notes );
      

      【讨论】:

        【解决方案3】:

        不要将PHP_EOL用于表单的textarea进行数组,使用它:

        array_values(array_filter(explode("\n", str_replace("\r", '', $_POST['data']))))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-01
          • 1970-01-01
          • 2022-01-16
          • 1970-01-01
          • 2011-12-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多