PHP将字符串分成几部分
I have a string $str which holds the below information
Cricket Batting:India Score:99/2 Date:27 June 2013
I want break this string into 4 parts and that should be like this:
$part1 = "Cricket";
$part2 = "Batting:India";
$part3 = "Score:99/2";
$part4 = "Date:27 June 2013";
I tried using explode() but the problem is values doesn't stand same always. For example it could be:
Cricket Batting:South Africa Score:203/10 Date:7 May 2013
or this:
Cricket Batting:Australia Score:1/1 Date:27 September 2019
So, when I use explode South and africa will split into different variables. I can't use wordwrap() as length of the string varies from time to time.
我有一个字符串$ str,其中包含以下信息 p>
Cricket 击球:印度得分:99/2日期:2013年6月27日 blockquote>我想把这个字符串分成4个部分,应该是这样的: p>
$ part1 =“Cricket”; $ part2 =“击球:印度”; $ part3 =“得分:99/2”; $ part4 =“日期:2013年6月27日”; \ n code> pre>
我尝试使用explode(),但问题是值始终不相同。 例如,它可能是: p>
板球击球:南非得分:203/10日期:2013年5月7日\或者: Cricket击球:澳大利亚得分:1/1日期 :2019年9月27日 code> pre>
所以,当我使用爆炸南方和非洲将分裂成不同的变量。 我不能使用wordwrap(),因为字符串的长度会不时变化。 p> div>
You can use preg_split with this pattern:
~ (?=Batting|Score|Date)~
The preg_split function is the best solution in this case:
preg_split('/\s(?=\w+:)/ ', $str);
Splitting point explained below:
\s
- matches one space
(?=\w+:)
- positive lookahead matching a word followed by a colon