Question

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!

Was it helpful?

Solution

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"
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top