在PHP中拆分动态字符串

时间:2013-11-29 18:06:03

标签: php

我在PHP中有以下字符串:

System load: 0.0 Processes: 119 Usage of /: 0.8% of 226.04GB Users logged in: 1 Memory     usage: 4% IP address for eth0: 192.168.0.21 Swap usage: 0% Graph this data and manage this system at https://landscape.canonical.com/ 

我正在尝试将其拆分为每个值的字符串,因此我可以得到“0.0”,“119”,“226.04GB的0.8%”,“1”,“4%”,“192.168.0.21” ,“0%”。

我确实尝试在字符串中使用设置位置来挑选数据但是意识到它并不好,因为值是动态的,并且可以随时从1到4个字符变长。有没有办法可以使用PHP拆分它们?我无法在字符串函数库中找到任何内容。感谢。

3 个答案:

答案 0 :(得分:2)

http://www.phpliveregex.com/p/2kT

$input = 'System load: 0.0 Processes: 119 Usage of /: 0.8% of 226.04GB Users logged in: 1 Memory     usage: 4% IP address for eth0: 192.168.0.21 Swap usage: 0% Graph this data and manage this system at https://landscape.canonical.com/';

$results = array();

preg_match_all("/\d[^\s:]*/", $input, $results);

$结果将如下所示:

Array
(
    [0] => Array
        (
            [0] => 0.0
            [1] => 119
            [2] => 0.8%
            [3] => 226.04GB
            [4] => 1
            [5] => 4%
            [6] => 0
            [7] => 192.168.0.21
            [8] => 0%
        )

)

答案 1 :(得分:0)

正在抓取组(未经测试)的正则表达式示例:

System load: (\d+.\d) Processes: (\d+) Usage of /: (\d+.\d)% of (\w+) Users logged in: (\d+) Memory usage: (\d+%) IP address for eth0: (\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}) Swap usage: (\d+%) Graph this data and manage this system at https://landscape.canonical.com/ 

它很容易受到轻微变化的影响,比如额外的空间等。从df等不同地方获取这些信息要容易得多。有些甚至可用作标准PHP函数,如sys_getloadavg()

答案 2 :(得分:0)

$str = 'System load: 0.0 Processes: 119 Usage of /: 0.8% of 226.04GB Users logged in: 1 Memory     usage: 4% IP address for eth0: 192.168.0.21 Swap usage: 0% Graph this data and manage this system at https://landscape.canonical.com/';  

$regex = '/^(?:System\s+load\:\s+)(\d+\.\d+)(?:\s+Processes\:\s+)(\d+)(?:\s+Usage\s+of\s+\/\:\s+)(\d+\.\d+\%\sof\s\d+\.\d+GB)(?:\s+Users\s+logged\s+in\:\s+)(\d+)(?:\s+Memory\s+usage\:\s+)(\d+\%)(?:\s+IP\s+address\s+for\s+eth\d+\:\s+)(\d+\.\d+\.\d+\.\d+)(?:\s+Swap\s+usage\:\s+)(\d+\%)(?:\s+Graph\s+this\s+data.+)$/';  

preg_match_all($regex, $str, $x);  

echo '<pre>'.print_r($x, 1);  

不要担心空格;)