tags:

views:

70

answers:

4

I'm looking to extract 2 elements from a string into an array. The string is a weather feed:

Thursday at 08:00 BST: white cloud. 10°C (50°F)

I want the "white cloud" and "10°C" parts. So I need to match between "BST:" and "." as well as between " " and "°C".

I'm struggling with the regular expression(s) I need and would really appreciate the help!

+3  A: 

Try this regular expression:

^\w+ at \d{2}:\d{2} BST: ([^.]+)\. (-?\d+°C)

If there is not a single space between the words, replace them with \s+.

Gumbo
A: 

Something like:

/BST: (.*) ([0-9]+°C)/

Should work although you may have a problem matching the ° if do try:

/BST: (.*) ([0-9]+.C)/
Neel
+2  A: 

Something like this should do:

preg_match('/: (.*?)\. (-?\d+)/', $str, $matches);

Things to watch out for:

  • Don't match on BST or it'll break in winter when we move to GMT
  • Watch out for negative temperatures
Greg
Good point on not matching against `BST`!
Stefan Gehrig
Works a charm, excellent advice about the BST.
Wil
A: 

You can use capture groups. Anything within round parantheses will be captured (by default) and you can fetch what they matched later:

:\s+([^.]*)\s+([\d]*)

If that is your regular expression you can use it with preg_match:

$matches = array();
preg_match('/:\s+([^.]*)\s+([\d]*)/', $string, $matches);

$matches will then contain the contents of the capture groups.

Joey