Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - PHP preg_split while keeping delimiter at the start of array element

I'm new to regex, and I want to split a string on a delimiter, while keeping that delimiter at the beginning of each array element. I tried it unsuccessfully, and came up with:

    $str = 'LOTS OF STUFF AND SOME MORE STUFF AND SOME OTHER STUFF';
    $matches = preg_split('/( AND)/', $str, null, PREG_SPLIT_DELIM_CAPTURE);  

This puts the delimiter as its own element :

[0]=>"LOTS OF STUFF"
[1]=>" AND"
[2]=>" SOME MORE STUFF"
[3]=>" AND"
[4]=>" SOME OTHER STUFF"

But I wanted to keep the delimiter at the beginning of the element:

[0]=>"LOTS OF STUFF"
[1]=>" AND SOME MORE STUFF"
[2]=>" AND SOME OTHER STUFF"

I thought maybe I could do it trying to use a look-behind, but then I was losing the delimiter again:

    $matches = preg_split('/(?<=s)AND/', $str, null, PREG_SPLIT_DELIM_CAPTURE);

[0]=>"LOTS OF STUFF"
[1]=>" SOME MORE STUFF"
[2]=>" SOME OTHER STUFF"

Would love some help, thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use lookahead assertion ((?=)) to split at the string positions followed by AND:

$str = 'LOTS OF STUFF AND SOME MORE STUFF AND SOME OTHER STUFF';
$matches = preg_split('/ (?=AND)/', $str); 
var_dump($matches);
/*
array(3) {
  [0]=>
  string(13) "LOTS OF STUFF"
  [1]=>
  string(19) "AND SOME MORE STUFF"
  [2]=>
  string(20) "AND SOME OTHER STUFF"
}
*/  

Demo. This code removes whitespace preceding AND; if it's not what you want, just get rid off the whitespace in the regex.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...