[英]Regex for any number followed by space and then a string with spaces
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.我需要的最接近结果的是这个正则表达式:
\d+^[ a-zA-Z]
,但它是不完整的。
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谢谢大家的帮助
You can use preg_split
:您可以使用
preg_split
:
preg_split('~\s+(?=\d)~', $s)
This regex matches one or more whitespace chars before a digit.此正则表达式匹配数字前的一个或多个空白字符。 See the regex demo .
请参阅正则表达式演示。
$s = '12 Cheeseburger bacon 2 Chips 3 Coke';
print_r(preg_split('~\s+(?=\d)~', $s));
Output: 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.此模式
\d+^[ a-zA-Z]
匹配 1+ 位,然后使用不正确的^
断言字符串的开头。 Then it matches a single char out of [ a-zA-Z]
然后它匹配
[ 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.您可以得到 3 个结果,其后有匹配的数字和匹配的字符 a-zA-Z,其中重复前面有一个空格。
\b\d+(?:\h+[A-Za-z]+)+\b
\b
A word boundary \b
一个词的边界\d+
Match 1+ digits \d+
匹配 1+ 个数字(?:
Non capture group (?:
非捕获组
\h+[A-Za-z]+
Match 1+ spaces and 1+ times any of the ranges A-Za-z \h+[A-Za-z]+
匹配 1+ 个空格和 1+ 次任意范围 A-Za-z)+
Repeat 1+ times )+
重复 1+ 次\b
A word boundary \b
一个词的边界Regex demo |正则表达式演示| Php demo
Php 演示
$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 Output
Array
(
[0] => 12 Cheeseburger bacon
[1] => 2 Chips
[2] => 3 Coke
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.