I have a string variable named $message
as below:
* Time Stamp: 2012-12-03 16:36:04
* Speed: 7 km/h
* Heading: 356 deg (N)
* Event ID: -48
* Event Desc: .Arrived at Inbound Receiving
* Event Value: -56
* Event Value Type: 0
I then try to extract the event and timestamp values from the variable with the below code:
$event = null;
$lines = explode(PHP_EOL, $message);
foreach($lines as $line) {
// skip empty lines
if(strlen($line) == 0) {
continue;
}
$tokens = explode(':', $line);
// tokens[0] contains the key , e.g. Event Value
// tokens[1]~[N] contains the value (where N is the number of pieces), e.g. -56
// stitch token 1 ~ N
$key = $tokens[0];
unset($tokens[0]);
$val = implode(': ', $tokens);
// do your extra logic here, e.g. set $event variable to value
if(strpos($key, 'Event Desc') > -1) {
$event = $val;
}
if(strpos($key, 'Time Stamp') > -1) {
$time = $val;
}
}
This works great, only problem is that the returned values are:
.Arrived at Arrived at Inbound Receiving =
2012-12-03 16:36:04 =
Where does the equal sign come from and how can I remove it along with the trailing spaces?
my expected result would be:
.Arrived at Arrived at Inbound Receiving
and
2012-12-03 16:36:04
This is how it appears in the string variable. Thanks as always.
You can try
preg_match_all("/ ([a-z ]+):([a-z0-9:\-. ]+)/i", $string,$match);
$values = array_combine($match[1], $match[2]) ;
echo $values['Time Stamp'] ,PHP_EOL ;
echo $values['Speed'] ,PHP_EOL ;
echo $values['Heading'] ,PHP_EOL ;
echo $values['Event Desc'] ,PHP_EOL ;
// .... etc
Output
2012-12-03 16:36:04
7 km
356 deg
.Arrived at Inbound Receiving