PHP preg_split while keeping delimiter at the start of array element

后端 未结 1 1740
抹茶落季
抹茶落季 2020-12-21 22:47

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 w

相关标签:
1条回答
  • 2020-12-21 23:21

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题