making print_r use PHP_EOL

前端 未结 5 838
逝去的感伤
逝去的感伤 2021-01-13 23:42

My PHP_EOL is \"\\r\\n\", however, when I do print_r on an array each new line has a \"\\n\" - not a \"\\r\\n\" - placed after it.

Any idea if it\'s pos

5条回答
  •  有刺的猬
    2021-01-14 00:31

    Like pointed out elsewhere on this page, the newlines are hardcoded in the PHP source, so you have to replace them manually.

    You could use your own version of print_r like this:

    namespace My;
    
    function print_r($expression, $return = false)
    {
        $out = \print_r($expression, true);
        $out = \preg_replace("#(?

    Whenever you want to use it, you just import it with

    // aliasing a function (PHP 5.6+)
    use My\print_r as print_r;
    
    print_r("A string with \r\n is not replaced");
    print_r("A string with \n is replaced");
    

    This will then use PHP_EOL for newlines. Note that it will only substitute newlines, e.g. \n, but not any \r\n you might have in the $expression. This is to prevent any \r\n to become \r\r\n.

    The benefit of doing it this way is that it will work as a drop-in replacement of the native function. So any code that already uses the native print_r can be replaced simply by adding the use statement.

提交回复
热议问题