【问题标题】:php5 copy sub-strings from string separated by space?php5从用空格分隔的字符串中复制子字符串?
【发布时间】:2016-07-20 22:16:33
【问题描述】:

我正在使用 php5 并且有一个脚本可以返回客户端的 IP 地址。 使用 shell_exec() 函数执行脚本。现在输出是这样的:*192.168.10.40 192.168.10.41 *。 现在我需要将它存储在一个数组中。我使用了 preg_match() 但它不起作用。

这是使用 preg_match() 的代码:

$test = shell_exec("/www/dhcp.sh");
$pattern='/([^ ]*) /';
preg_match($pattern, $test, $new);

preg_match() 返回 0;

这是我使用的explode():

$test = shell_exec("/www/dhcp.sh");
var_dump( explode(' ', $test ) );

我也使用了爆炸,但我得到的结果是: array(1) { [0]=> string(28) "192.168.10.40 192.168.10.41" } 谁能告诉我如何将字符串拆分为数组?

问候,
苏米亚

【问题讨论】:

  • 你应该显示你正在使用的代码。

标签: php php-5.3 php-5.6


【解决方案1】:

你可以使用explode来拆分你的字符串:

explode(' ', '192.168.10.40 192.168.10.41'));

给你

array(2) {
  [0]=>
  string(13) "192.168.10.40"
  [1]=>
  string(13) "192.168.10.41"
}

http://php.net/manual/fr/function.explode.php

【讨论】:

  • IP 地址将发生变化,如果设备未连接,脚本可能不返回任何内容。
  • 那么你必须在爆炸字符串之前验证你的脚本返回的字符串不为空
  • 是的,脚本没有返回空。但是我必须将 shell_script() 的输出传递给explode函数。我可以作为参数传递吗?
  • 那么你的脚本的确切输出是什么?你想传递什么样的论点?
  • 脚本的输出会是这样的:192.168.10.40 192.168.10.41
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
相关资源
最近更新 更多