PHP, return a set number of characters after finding the string in a string(variable)

StackOverflow https://stackoverflow.com/questions/13698876

  •  04-12-2021
  •  | 
  •  

Pergunta

I am trying to fetch details from an email pipe. the pipe returns the $message variable to me which contains allot of data. I want to be able to search the string for a specific value and return the next 'x' amount of characters.

as an example, my variable $message contains the below string:

Arrived at Inbound Receiving occurred

on M03-Actros 33.50 (1231) (MX1) (LT) 1022 on 2012-12-03

16:36:04



               * Driver ID: person, RT (1231) 

                * Vehicle Desc: M03-Actros 33.50 (1234) (MX1) (LT) 

                * Vehicle ID: 1022 

                * Time Stamp: 2012-12-03 16:36:04 

                * Latitude: S31 11.870' 

                * Longitude: E031 44.555' 

                * 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 want to filter out the Event Desc. so search $message for string 'Event Desc:' and then return the remaining data on that line. so from the above example I want to set the value of variable '$event' to '.Arrived at Inbound Receiving'

I know I have to use

if (strstr($subject, 'Event Desc: ')) {

}

but am not sure how to then return the remaining data on row given that the data can vary in length.

Any help appreciated as always, Thanks.

Foi útil?

Solução

I suggest this:

$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;
  }
}

Limitation: your data cannot contain :

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top