regex - Split string to gather data with PHP



I need to split this string into different section to gather particular data so that I can store it in a database with PHP. I am after some help to either split or use a regex to gather this data reliably. Not all the values will be the same length, so need a way to test for each part without just splitting based on character position.

Sol 1565 (Dec 31, 2016): Sunny, high -6C/21F, low -72C/-97F, pressure at 8.74 hPa, daylight 06:25-18:41

I want to get these separate values:

  • Sol 1565 (This will always start with Sol and be followed by a 4 digit number)
  • Dec 31, 2016 (The date format will always be M d, Y)
  • Sunny (A word will always be used, but may not be the same word)
  • -6C [high] (The high temp in C)
  • 21F [high] (The high temp in F)
  • -72C [low] (The low temp in C)
  • -97F [low] (The low temp in F)
  • 8.74 (The pressure - will be a float)
  • 06:25 (daytime start)
  • 18:41 (daytime finish)

Edit: I have tried using substr, but soon worked out it would not be reliable. So after a solution that would be more suitable.

1 Answer: 

At first you have to understand regex syntax then you can do easily. Here is reference:

I have made one to make you understand. Hope then you can do from your end.

$pattern = '@(high\s)([-+/0-9a-zA-Z]+)@';
$subject = 'Sol 1565 (Dec 31, 2016): Sunny, high -6C/21F, low -72C/-97F, pressure at 8.74 hPa, daylight 06:25-18:41';
$result = preg_match( $pattern, $subject , $matches );

And result:

    [0] => high -6C/21F
    [1] => high 
    [2] => -6C/21F

You will get high value $matches[2]. And then you can use explode() to get C and F.

Just I am showing a partial solution. You can apply alternative pattern after reading regex syntax.