PHP 中 exec 的输出问题

发布于 2024-10-03 13:01:04 字数 632 浏览 1 评论 0原文

你好,我正在尝试在 PHP 中输​​出我的内存使用情况。

我的代码如下所示:

exec('free -m', $out);
var_dump($out[1]);
list($mem, $total, $used, $free, $shared, $buffers, $cached) = explode(" ", $out[1]);
echo "Memory: " .$used. "/" . $total;

现在问题是文本打印

Memory: /

var_bump 给了我这个:

string(73) "Mem: 3024 1968 1055 0 159 608"

这个字符串不应该是 (73) 而应该是 (29)。 如果我制作自己的数组,则完全没有问题:

$out = array('','Mem: 3024 2020 1003 0 121 708','');
string(29) "Mem: 3024 1968 1055 0 159 608"

任何人都可以给我一个解决方案或调试此问题的下一步吗?

最诚挚的问候, 艾伦

Hello I am trying to output my memory use in PHP.

My code looks like this:

exec('free -m', $out);
var_dump($out[1]);
list($mem, $total, $used, $free, $shared, $buffers, $cached) = explode(" ", $out[1]);
echo "Memory: " .$used. "/" . $total;

Now the problem is that the text prints

Memory: /

And the var_bump gives me this:

string(73) "Mem: 3024 1968 1055 0 159 608"

This string should not be (73) but (29).
If I make my own array there is no problems at all:

$out = array('','Mem: 3024 2020 1003 0 121 708','');
string(29) "Mem: 3024 1968 1055 0 159 608"

Can anyone give me a solution or a next step in debugging this?

Best Regards,
Allan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岛歌少女 2024-10-10 13:01:04

当我运行 free -m 时,我实际上得到了大约 73 个字符(其中有很多空格):

Mem:          2047          0       2047          0          0          0

我想您会发现这就是导致您的 used为空的原因>total 值:explode 正在拾取 Mem:2047 之间空格中的空字符串。

一种解决方案是使用 preg_split分隔符为“/\s+/”

When I run free -m, I actually get about 73 characters (lots of spaces in there):

Mem:          2047          0       2047          0          0          0

I think you'll find that's what's causing your empty used and total values: explode is picking up the empty strings somewhere in those spaces between Mem: and 2047.

One solution is to use preg_split with a separator of "/\s+/".

灰色世界里的红玫瑰 2024-10-10 13:01:04

删除空格,例如:

explode(" ", preg_replace('/\s+/', ' ', $out[1]));

Remove the spaces such as :

explode(" ", preg_replace('/\s+/', ' ', $out[1]));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文