PHP中的字符串切片/字符串操作

时间:2012-07-17 15:35:26

标签: php substr strpos

Total accesses: 296282 - Total Traffic: 1.2 GB
CPU Usage: u757.94 s165.33 cu0 cs0 - 2.56% CPU load
8.22 requests/sec - 33.5 kB/second - 4175 B/request
22 requests currently being processed, 26 idle workers

假设我们将上面的字符串作为字符串,并将该字符串存储在变量中。 问题:我希望得到以下值:

  1. 请求/秒 - 当前值为8.22
  2. 当前正在处理的请求 - CURRENT VALUE IS 22
  3. 闲置工人 - 当前价值是26
  4. 使用 strpos substr 完成一些解决方案,但我认为它不是一个好的解决方案,因为上面的值是动态的,可能是2位数或4位数或更长

    示例代码:

    $rps = substr($data,strpos($data,"requests/sec")-5,4);
    echo $rps; //displays 8.22
    

    还有其他办法吗?我将不胜感激任何回应:)

3 个答案:

答案 0 :(得分:4)

正则表达式。

$values = array();
preg_match("/(?P<rps>[\d.]+) requests\/sec(.*)(?P<requests>[\d]+) requests (.*)(?P<workers>[\d]+) idle workers/", $your_text, $values);

print 
"requests/sec - CURRENT VALUE IS {$values['rps']}
 requests currently being processed - CURRENT VALUE IS {$values['requests']}
 idle workers - CURRENT VALUE IS {$values['workers']}";

答案 1 :(得分:3)

正则表达式可行:

<?php
$data = 'Total accesses: 296282 - Total Traffic: 1.2 GB
CPU Usage: u757.94 s165.33 cu0 cs0 - 2.56% CPU load
8.22 requests/sec - 33.5 kB/second - 4175 B/request
22 requests currently being processed, 26 idle workers';

if( preg_match('/(\d*\.?\d*)\srequests\/sec/', $data, $m) ){
    echo $m[1];
}else{
    echo 'no match';
}

答案 2 :(得分:2)

假设所有输出都在字符串变量$ output中。你可以这样做:

// requests per second
$regex = '#^([0-9]*\.?[0-9].*)\040requests/sec#';
preg_match($regex, $output, $matches);
$req_per_sec = $matches[1];

// request being processed
$regex = '/([0-9]*)\040requests\040currently/';
preg_match($regex, $output, $matches);
$req_processed = $matches[1];

// idle workers
$regex = '/\040([0-9]*)\040idle\040workers/';
preg_match($regex, $output, $matches);
$idle_workers = $matches[1];