Search code examples
phpregexpreg-split

preg_split using PREG_SPLIT_DELIM_CAPTURE


I was looking to split a string based on a regular expression but I also have interest in keeping the text we split on:

php > var_dump(preg_split("/(\^)/","category=Telecommunications &     CATV^ORcategory!=ORtest^caused_byISEMPTY^EQ"), null, PREG_SPLIT_DELIM_CAPTURE);
array(4) {
  [0]=> string(34) "category=Telecommunications & CATV"
  [1]=> string(18) "ORcategory!=ORtest"
  [2]=> string(16) "caused_byISEMPTY"
  [3]=> string(2) "EQ"
}
NULL
int(2)

What I do not understand is why am I not getting an array such as:

array(4) {
  [0]=> "category=Telecommunications & CATV"
  [1]=> "^"
  [2]=> "ORcategory!=ORtest"
  [3]=> "^"
  [4]=> "caused_byISEMPTY"
  [5]=> "^"
  [6]=> "EQ"
}

Additionally, how could I change my regular expression to match "^OR" and also "^". I was having trouble with a lookbehind assertion such as:

$regexp = "/(?<=\^)OR|\^/"; 

Solution

  • This will work as expected:

    var_dump(preg_split('/(\^)/','category=Telecommunications &     CATV^ORcategory!=ORtest^caused_byISEMPTY^EQ', -1, PREG_SPLIT_DELIM_CAPTURE));
    

    the closing bracket of preg_split() is at the wrong place.

    additional question:

    /(\^OR|\^)/