2

I'm simply experimenting with PHP to prepare me for some upcoming projects and I've encountered a string which won't have <br /> inserted into it even though it is a multi-line string.

The code is simple PHP (which I've enclosed in simple html tags)

$ping = passthru('ping www.google.com');
$ping = htmlspecialchars_decode($ping);
$ping = strip_tags($ping);
$ping = nl2br($ping);
echo $ping;

The result is a multi-line string but without any <br /> tags added, however, the page source shows the result as a mutli-line string so there's definitely multiple lines there but nl2br() is not doing anything.

Page source (which has mysteriously added extra whitespace lines when I pasted it in here)

<html>

    <head>

        <title>Derp</title>



    </head>

    <body><p>



Pinging www.l.google.com [209.85.227.147] with 32 bytes of data:

Reply from 209.85.227.147: bytes=32 time=44ms TTL=48

Reply from 209.85.227.147: bytes=32 time=28ms TTL=48

Reply from 209.85.227.147: bytes=32 time=40ms TTL=48

Reply from 209.85.227.147: bytes=32 time=29ms TTL=48



Ping statistics for 209.85.227.147:

    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

    Minimum = 28ms, Maximum = 44ms, Average = 35ms

</p>

    </body>

</html>

And the actual string shown on the webpage:

Pinging www.l.google.com [209.85.227.147] with 32 bytes of data: Reply from 209.85.227.147: bytes=32 time=30ms TTL=48 Reply from 209.85.227.147: bytes=32 time=29ms TTL=48 Reply from 209.85.227.147: bytes=32 time=28ms TTL=48 Reply from 209.85.227.147: bytes=32 time=31ms TTL=48 Ping statistics for 209.85.227.147: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 28ms, Maximum = 31ms, Average = 29ms

After extensive Googling all I can find is people who are not using nl2br() when they should be

What am I missing here?

4

2 回答 2

3
<?php 
$ping = `ping www.google.com`;
$ping = nl2br($ping);
echo $ping;
?>

<br />
Pinging www.l.google.com [209.85.147.104] with 32 bytes of data:<br />
<br />
Reply from 209.85.147.104: bytes=32 time=24ms TTL=53<br />
Reply from 209.85.147.104: bytes=32 time=23ms TTL=53<br />
Reply from 209.85.147.104: bytes=32 time=23ms TTL=53<br />
Reply from 209.85.147.104: bytes=32 time=25ms TTL=53<br />
<br />
Ping statistics for 209.85.147.104:<br />
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),<br />

Approximate round trip times in milli-seconds:<br />
    Minimum = 23ms, Maximum = 25ms, Average = 23ms<br />
于 2011-08-01T20:06:01.687 回答
1

你误解了什么passthru($cmd)。它执行$cmd,但stdout直接发送到浏览器 - 您不会将结果作为字符串返回。相反,它返回被调用的返回码$cmd

如果要捕获输出,请使用exec并通过$output引用传递数组。

于 2011-08-01T20:09:44.473 回答