4
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

Let say we have the above as string and we store that string in a variable. Problem: I want to get the VALUE of the following:

  1. requests/sec - CURRENT VALUE IS 8.22
  2. requests currently being processed - CURRENT VALUE IS 22
  3. idle workers - CURRENT VALUE IS 26

Done some solution using strpos and substr but i dont think its a good solution at all because those values above are dynamic it could be 2 digits or 4 digits or longer.

sample code:

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

Is there another way to do this? I will appreciate any response :)

lidongghon
  • 323
  • 3
  • 14

3 Answers3

4

Regular expressions.

$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']}";
madfriend
  • 2,400
  • 1
  • 20
  • 26
3

Regular expression would work:

<?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';
}
Chris
  • 1,118
  • 8
  • 24
2

Assuming all of that output is in string variable $output. You could do this:

// 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];
Mike Brant
  • 70,514
  • 10
  • 99
  • 103