PHP Simple way to replace or remove empty lines with str_replace

前端 未结 3 1105
别那么骄傲
别那么骄傲 2021-01-14 07:41
$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

相关标签:
3条回答
  • 2021-01-14 08:03

    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);
    
    0 讨论(0)
  • 2021-01-14 08:11

    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
    0 讨论(0)
  • 2021-01-14 08:12

    str_replace can be passed an array as:

    $line_out = str_replace(array("\r","\n"), '', $line_in);
    
    0 讨论(0)
提交回复
热议问题