我是regex的新手,我想在分隔符上分割一个字符串,同时在每个数组元素的开头保留该分隔符。我没试成功,但提出了:
$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"
非常乐意帮助,谢谢!!
答案 0 :(得分:7)
使用lookahead assertion((?=)
)分隔跟随的字符串位置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。此代码删除AND
之前的空格;如果它不是你想要的,只要摆脱正则表达式中的空白。