我是正则表达式的新手,我想在分隔符上拆分字符串,同时将该分隔符保留在每个数组元素的开头。我尝试了它不成功,并想出了:
$str = 'LOTS OF STUFF AND SOME MORE STUFF AND SOME OTHER STUFF';
$matches = preg_split('/(\ AND)/', $str, null, PREG_SPLIT_DELIM_CAPTURE);
这将分隔符作为自己的元素:
[0]=>"LOTS OF STUFF"
[1]=>" AND"
[2]=>" SOME MORE STUFF"
[3]=>" AND"
[4]=>" SOME OTHER STUFF"
但我想将分隔符保留在元素的开头:
[0]=>"LOTS OF STUFF"
[1]=>" AND SOME MORE STUFF"
[2]=>" AND SOME OTHER STUFF"
我想也许我可以尝试使用后视来做到这一点,但后来我又失去了分隔符:
$matches = preg_split('/(?<=\s)AND/', $str, null, PREG_SPLIT_DELIM_CAPTURE);
[0]=>"LOTS OF STUFF"
[1]=>" SOME MORE STUFF"
[2]=>" SOME OTHER STUFF"
希望得到一些帮助,谢谢!!