Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String slicing / string manipulation in PHP

Tags:

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

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 :)

like image 872
lidongghon Avatar asked Jan 17 '23 02:01

lidongghon


1 Answers

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']}";
like image 59
madfriend Avatar answered Jan 18 '23 23:01

madfriend