1

我是正则表达式的新手,我想在分隔符上拆分字符串,同时将该分隔符保留在每个数组元素的开头。我尝试了它不成功,并想出了:

    $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"

希望得到一些帮助,谢谢!!

4

1 回答 1

8

使用前瞻断言( (?=)) 在字符串位置拆分,后跟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;如果这不是您想要的,只需去掉正则表达式中的空格。

于 2013-10-31T21:47:05.513 回答