PHP preg_split,同时在数组元素的开头保留定界符 [英] PHP preg_split while keeping delimiter at the start of array element
问题描述
我是regex的新手,我想在分隔符上拆分字符串,同时在每个数组元素的开头保留该分隔符.我尝试失败,然后想到了:
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!!
推荐答案
使用 超前断言 ((?=)
)在跟在的字符串位置处被AND
分开:
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"
}
*/
演示 .此代码删除AND
之前的空格;如果这不是您想要的,那就摆脱正则表达式中的空白.
Demo. This code removes whitespace preceding AND
; if it's not what you want, just get rid off the whitespace in the regex.
这篇关于PHP preg_split,同时在数组元素的开头保留定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!