我有一个名为$message
的字符串变量,如下所示:
* 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
然后我尝试使用以下代码从变量中提取事件和时间戳值:
$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;
}
}
这很有效,唯一的问题是返回的值是:
.Arrived at Arrived at Inbound Receiving =
2012-12-03 16:36:04 =
等号来自何处以及如何将其与尾随空格一起删除?
我的预期结果是:
.Arrived at Arrived at Inbound Receiving
和
2012-12-03 16:36:04
这是它在字符串变量中的显示方式。 一如既往地谢谢。
答案 0 :(得分:2)
你可以尝试
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
输出
2012-12-03 16:36:04
7 km
356 deg
.Arrived at Inbound Receiving
答案 1 :(得分:1)
这将为您提供正确的密钥和价值。
list($key, $value) = explode(':', $line, 2);
$key = trim($key);
$value = trim(quoted_printable_decode($value));
答案 2 :(得分:1)
我的猜测是你从电子邮件中收到了$message
个内容。如果是这种情况,请先尝试通过quoted_printable_decode运行内容。
答案 3 :(得分:0)
如果您使用
echo $time;
echo $event;
它将显示2012-12-03 16:36:04。仅限入站接收