简体   繁体   中英

PHP Regular expression to create an array

I have a string which is pulled from iCal, which outputs the description. I want to take the description each time and create an array with the objects I need. They always follow the same pattern.

For example I have:

Description: Trip status: Confirmed\n \n FLIGHT INFORMATION: \n \n United Airlines UA 485: \n \n \n From: Newark Liberty International (New York, USA) - TerminalC at Fri, Sep 28, 2012 16:34 (local time) \n To: Denver International (Denver, USA) at Fri, Sep 28, 2012 18:47 (local time) \n Cabin: Economy Restricted\n Duration: 04:13\n Stop(s): 0\n Aircraft: Boeing 757-200\n

and then

Description: Trip status: Confirmed\n \n FLIGHT INFORMATION: \n \n Air Canada AC 1072: \n \n \n From: Denver International (Denver, USA) at Sat, Sep 29, 2012 10:55 (local time) \n To: P Trudeau International (Montreal, Canada) at Sat, Sep 29, 2012 16:29 (local time) \n Cabin: Economy Restricted\n Duration: 03:34\n Stop(s): 0\n Aircraft: Airbus Industrie A319\n

As you can see the different outputs follow the same structure, so in an ideal world I would want:

$itinery[0]: Confirmed
$itinery[1]: United Airlines UA 485
$itinery[2]: Newark Liberty International (New York, USA)

Any guidance as ever is appreciated.

Thanks.

You could also break each line apart with explode()

$parts = explode ( $line, '\n' ) ;
print_r ( $parts ) ;

Then break the parts with explode ( $part[$i], ':' ) to get the values.

A more specific regex :

Description:\\s*Trip\\s+status:\\s+(\\w+)\\s*FLIGHT\\s+INFORMATION:\\s*([^:]+):\\s*From:\\s*([\\w\\d_,\\s-()]+)\\s+at\\s+(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat),

Following assumptions are made :

  • The "status" can contain only letters.
  • The "flight information" is supposed to end with a :
  • The "from" can contain only letters, numbers, one of those characters _,-() or blank characters. The "from" is immediately followed by this sequence : " at XXX" where XXX is a day (ie Sun,Mon,Tue,Wed,Thu,Fri or Sat).

Tips :
If status belongs to a closed list then replace (\\w+) with (?:Confirmed|Cancelled|Delayed) in the regex. Add other statuses if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM