PHP Simple way to replace or remove empty lines with str_replace

天大地大妈咪最大 提交于 2020-01-11 06:17:10

问题


$line-out = str_replace('\r', '', str_replace('\n', '', $line-in));

The above works for me but, I saw a [\n\r] example somewhere and I cannot seem to find it.

I just want to get rid any blank lines. The above is in a foreach loop.

Thanks for teaching.


回答1:


You shouldn't use - in variable names ;)

$line_out = preg_replace('/[\n\r]+/', '', $line_in);
$line_out = str_replace(array("\n", "\r"), '', $line_in);

Manual entries:

  • http://php.net/manual/en/function.preg-replace.php
  • http://php.net/manual/en/function.str-replace.php



回答2:


str_replace can be passed an array as:

$line_out = str_replace(array("\r","\n"), '', $line_in);



回答3:


This is from php.net's example #2 in str_replace (modified to suit the "environment"):

<?php
// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");

// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, '', $str);


来源:https://stackoverflow.com/questions/3779464/php-simple-way-to-replace-or-remove-empty-lines-with-str-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!