Search code examples
phpregexpreg-split

Break a sentence in two parts on first occurrence of a a number


I am in a situation that iIneed to break the line 'Havenlaan 86C Bus 12' into two parts

$str = 'Havenlaan 86C Bus 12'; 
$regex = '/[ ^\d]/';
$flags = PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY;
$exploded = preg_split( $regex,$str, 2, $flags);
print_r($exploded);

The above code sucessfully does the job and the out out is below.

  1. Havenlaan

  2. 86C Bus 12

BUT when I change the string to $str = 'Havenlaan ABC 86C Bus 12';

I get

1. Havenlaan
2. ABC 86C Bus 12

What I need is

1. Havenlaan ABC

2. 86C Bus 12

ie. first output should be pure string and second one should start with a number and can be followed by characters.


Solution

  • You can use lookahead

    $regex = '/(?=\d)/';
    

    This would split at the first occurrence of a digit (with the limit specified as 2).