Regex for any number followed by space and then a string with spaces

Viewed 358

i've tried a lot to find a way to split a string into an array and i found that regex can help me. What is most near the result i need is this regex: \d+^[ a-zA-Z], but it is incomplete.

My string is something like that:

$str = '12 Cheeseburger bacon 2 Chips 3 Coke'

and the result i need is an array containing this result:

[0] = 12 Cheeseburger bacon
[1] = 2 Chips
[2] = 3 Coke

Thank you all for helping

2 Answers

You can use preg_split:

preg_split('~\s+(?=\d)~', $s)

This regex matches one or more whitespace chars before a digit. See the regex demo.

See the PHP demo:

$s = '12 Cheeseburger bacon 2 Chips 3 Coke';
print_r(preg_split('~\s+(?=\d)~', $s));

Output:

Array
(
    [0] => 12 Cheeseburger bacon
    [1] => 2 Chips
    [2] => 3 Coke
)

This pattern \d+^[ a-zA-Z] matches 1+ digits and then asserts the start of the string using ^ which is not correct. Then it matches a single char out of [ a-zA-Z]

You can get the 3 results with matching digits and matching chars a-zA-Z after it where a space is preceded in the repetition.

\b\d+(?:\h+[A-Za-z]+)+\b
  • \b A word boundary
  • \d+ Match 1+ digits
  • (?: Non capture group
    • \h+[A-Za-z]+ Match 1+ spaces and 1+ times any of the ranges A-Za-z
  • )+ Repeat 1+ times
  • \b A word boundary

Regex demo | Php demo

$re = '/\b\d+(?:\h+[A-Za-z]+)+\b/';
$str = '12 Cheeseburger bacon 2 Chips 3 Coke';

preg_match_all($re, $str, $matches);
print_r($matches[0]);

Output

Array
(
    [0] => 12 Cheeseburger bacon
    [1] => 2 Chips
    [2] => 3 Coke
)
Related