为什么我的for循环不起作用?

时间:2014-11-28 20:56:37

标签: php for-loop

为什么我的for循环不起作用? $_POST["report"]是文本框的值。

<?php 
if($_SERVER["REQUEST_METHOD"]=="POST"){
 $report_output="Comment:\n";
 $report_output.=$_POST["report"];
    for($i=90;$i<=strlen($report_output);$i+=90){
            $report_output=substr_replace($report_output,"\n",int($i),0);
    };
    $report_output.="\n";
$file=fopen("report.txt","a");
fwrite($file,$report_output);
fclose($file);
}?>

2 个答案:

答案 0 :(得分:0)

我认为你要做的就是在每90个字符之后设置一个换行符。在您给我们的代码中,int()是一个未定义的函数,这就是循环无法工作的原因。如果您尝试将$i转换为整数,则可以执行此操作(int)$i。但是你不应该在这段代码中这样做,所以下面的内容没问题:

for($i=90;$i<=strlen($report_output);$i+=90){
        $report_output=substr_replace($report_output,"\n",$i,0);
};

答案 1 :(得分:0)

你也可以按照以下方式做你想做的事情:

<?php

if( $_SERVER["REQUEST_METHOD"] == "POST" ){
    $report_output = "Comment:\n";
    $report_output .= htmlspecialchars( $_POST["report"] );

    $split = str_split( $report_output, 90 );
    foreach ( $split as $portion ){
        $str .= trim( $portion ) . "\n";
    }

   $report_output = $str . "\n"; 

   $file = fopen( "report.txt","a" );
   fwrite( $file,$report_output );
   fclose( $file );
}

请注意,不建议在没有 first 的情况下立即使用POST(或GET)变量,以确保此表单数据不受污染。在这种情况下,我使用了htmlspecialchars(),但您可能希望采取其他预防措施,以确保您的数据真正符合您的预期,以避免潜在的安全问题。