Iterate over each line in a string in PHP

前端 未结 7 2143
我寻月下人不归
我寻月下人不归 2020-11-28 18:55

I have a form that allows the user to either upload a text file or copy/paste the contents of the file into a textarea. I can easily differentiate between the two and put wh

7条回答
  •  孤城傲影
    2020-11-28 19:28

    foreach(preg_split('~[\r\n]+~', $text) as $line){
        if(empty($line) or ctype_space($line)) continue; // skip only spaces
        // if(!strlen($line = trim($line))) continue; // or trim by force and skip empty
        // $line is trimmed and nice here so use it
    }
    

    ^ this is how you break lines properly, cross-platform compatible with Regexp :)

提交回复
热议问题