0

I have been trying to create a regex expression which only selects the whitespace between numbers, which preg_split can split.

For example:

$string = "Unit 54 981 Mayne Street";

Would return as:

array() { 
  [0]=> "Unit 54" 
  [1]=> "981 Mayne Street" 
}

I have had no luck so far. Any help would be greatly appreciated!

Sam-
  • 28
  • 5
  • Look into lookahead & behinds: as they are officially not part of the match, they will be preserved, and only the whitespace is removed in the splitting. – Wrikken Jan 29 '14 at 21:36
  • Thank you! That is what I was trying but I must have missed something in my attempt. – Sam- Jan 29 '14 at 21:43

1 Answers1

1

Try using lookaround assertions, like this:

$result = preg_split('/(?<=\d)\s+(?=\d)/', $string);

This will match any sequence of one or more whitespace characters that are immediately preceded and followed by a digit character. It produces this array:

Array (
    [0] => "Unit 54"
    [1] => "981 Mayne Street"
)
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • Thank you! That solves my problem exactly. My regex was so close, but fatally flawed. Apparently I have to wait seven minutes to be able to accept your answer. – Sam- Jan 29 '14 at 21:43
  • 1
    @Sam- Glad I could help. In the future though, make sure you include your attempts in the question. You'll get better results, and we can tell you where you went wrong. – p.s.w.g Jan 29 '14 at 21:44
  • Thanks, next time I will. – Sam- Jan 29 '14 at 21:51