0

我有一个字符串变量,命名$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

这就是它在字符串变量中的显示方式。一如既往地感谢。

4

4 回答 4

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  

在线演示

于 2012-12-04T10:34:17.350 回答
1

这将为您提供适当的密钥和价值。

list($key, $value) = explode(':', $line, 2);
$key = trim($key);
$value = trim(quoted_printable_decode($value));
于 2012-12-04T10:26:23.390 回答
1

我的猜测是您正在$message从电子邮件中获取内容。如果是这种情况,请先尝试通过quoted_printable_decode运行内容。

于 2012-12-04T10:26:23.263 回答
0

如果你使用

echo $time;
echo $event;

它将显示 2012-12-03 16:36:04 .Arrived at Inbound Receiving only

于 2012-12-04T10:24:31.353 回答