making print_r use PHP_EOL

前端 未结 5 843
逝去的感伤
逝去的感伤 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:39

    This may not be the most elegant solution, but you could capture the print_r() output using buffer output, then use str_replace() to replace existences of \n with your PHP_EOL. In this example I've replaced it with x to show that it's working...

    ob_start();
    
    $test_array = range('A', 'Z');
    print_r($test_array);
    
    $dump = ob_get_contents();
    ob_end_clean();
    

    As pointed out by dognose, since PHP 4.3 you can return the result of print_r() into a string (more elegant):

    $dump = print_r($test_array, true);
    

    Then replace line endings:

    $dump = str_replace("\n", "x" . PHP_EOL, $dump);
    echo $dump;
    

    Output:

    Arrayx
    (x
        [0] => Ax
        [1] => Bx
        [2] => Cx
        [3] => Dx
        [4] => Ex
        [5] => Fx
        [6] => Gx
        ... etc
        [25] => Zx
    )x
    

提交回复
热议问题