how to remove new lines and returns from php string?

后端 未结 10 1062
孤城傲影
孤城傲影 2020-12-24 01:06

A php variable contains the following string:

text

text2

  • item1
  • item2
相关标签:
10条回答
  • 2020-12-24 01:41

    You have to wrap \n or \r in "", not ''. When using single quotes escape sequences will not be interpreted (except \' and \\).

    The manual states:

    If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

    • \n linefeed (LF or 0x0A (10) in ASCII)

    • \r carriage return (CR or 0x0D (13) in ASCII)\

    • (...)

    0 讨论(0)
  • 2020-12-24 01:43

    Something a bit more functional (easy to use anywhere):

    function replace_carriage_return($replace, $string)
    {
        return str_replace(array("\n\r", "\n", "\r"), $replace, $string);
    }
    

    Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.

    0 讨论(0)
  • 2020-12-24 01:44
    $str = "Hello World!\n\n";
    echo chop($str);
    
    output : Hello World!
    
    0 讨论(0)
  • 2020-12-24 01:49

    Correct output:

    '{"data":[{"id":"1","reason":"hello\\nworld"},{"id":"2","reason":"it\\nworks"}]}'
    
    function json_entities( $data = null )
    {           
        //stripslashes
        return str_replace( '\n',"\\"."\\n",
            htmlentities(
                utf8_encode( json_encode( $data)  ) , 
                ENT_QUOTES | ENT_IGNORE, 'UTF-8' 
            )
        );
    }
    
    0 讨论(0)
  • 2020-12-24 01:50

    This should be like

    str_replace("\n", '', $str);
    str_replace("\r", '', $str);
    str_replace("\r\n", '', $str);
    
    0 讨论(0)
  • 2020-12-24 01:51

    You need to place the \n in double quotes.
    Inside single quotes it is treated as 2 characters '\' followed by 'n'

    You need:

    $str = str_replace("\n", '', $str);
    

    A better alternative is to use PHP_EOL as:

    $str = str_replace(PHP_EOL, '', $str);
    
    0 讨论(0)
提交回复
热议问题