Skip to content

Instantly share code, notes, and snippets.

@simbalinux
Created February 22, 2018 18:55
Show Gist options
  • Save simbalinux/9ea751b5c6c25ad32d9e31da268c2984 to your computer and use it in GitHub Desktop.
Save simbalinux/9ea751b5c6c25ad32d9e31da268c2984 to your computer and use it in GitHub Desktop.
search for host in string 2 PHP
<?php
//simulating the array from string:
$s = '
[2018-02-19 14:08:32] [info] status=GOOD&unit_status=GOOD&hostname=acme
[2018-02-19 14:08:32] [alert] Wrong status! (Not "DEGRADED")
[2018-02-19 14:08:37] [info] Request with params {"status":"GOOD","unit_status":"GOOD","hostname":"joe"}
[2018-02-19 14:08:37] [info] status=GOOD&unit_status=GOOD&hostname=joe
[2018-02-19 14:08:37] [alert] Wrong status! (Not "DEGRADED")
';
$lines=array();
$fp = fopen("../log/simplelogger.log", "r");
while(!feof($fp))
{
$line = fgets($fp);
array_push($lines, $line);
if (count($lines)>5)
array_shift($lines);
}
fclose($fp);
//$s = implode($lines)
$matches = [];
preg_match_all('#\b(status=.+)\b#', $s, $matches);
$rows = array_map(function($entry) {
$parsedStr = [];
parse_str($entry, $parsedStr);
return $parsedStr;
}, $matches[1]);
if(empty($rows)){
echo 'not found';
}else{
foreach($rows as $statusLine) {
echo 'hostname: '.$statusLine['hostname'].PHP_EOL;
echo 'status: '.$statusLine['status'].PHP_EOL;
echo 'unit_status: '.$statusLine['unit_status'].PHP_EOL.PHP_EOL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment