1

String:

"test AND test2 OR test3 AND test4"

PHP:

preg_split(\s?AND\s?|\s?OR\s?, $string);

Result:

["test", "test2", "test3", "test4"]

Wanted result:

["test", "test2", "test3", "test4"]
["AND", "OR", "AND"]

How can I get this result?

phpjssql
  • 471
  • 1
  • 4
  • 16
  • With [`PREG_SPLIT_DELIM_CAPTURE`](http://stackoverflow.com/questions/11758465/preg-split-how-to-include-the-split-delimiter-in-results) in between, or rather [`preg_match_all`](http://php.net/preg_match_all) and capture groups. – mario Aug 31 '15 at 10:05

2 Answers2

2

A way to separate captured delimiters when preg_split is used with the PREG_SPLIT_DELIM_CAPTURE option.

$string = "test AND test2 OR test3 AND test4";

$arr = preg_split('~\s*\b(AND|OR)\b\s*~', $string, -1, PREG_SPLIT_DELIM_CAPTURE);

$andor = [];
$test = [];

foreach($arr as $k=>$v) {
    if ($k & 1)
        $andor[] = $v;
    else
        $test[] = $v;
}

print_r($test);
print_r($andor);

$k & 1 is the bitwise operator AND. When the index $k is odd this means that the first bit is set to 1, then $k & 1 returns 1. (delimiters have always an odd index except if you use PREG_SPLIT_NO_EMPTY).

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

You can use preg_split and preg_match_all as

$str = "test AND test2 OR test3 AND test4";
$arr1 = preg_split('/\b(AND|OR)\b/', $str);
preg_match_all('/\b(AND|OR)\b/', $str, $arr2);
print_r($arr1);
print_r($arr2[0]);

Demo

Else simply use the answer suggested by @mario using PREG_SPLIT_DELIM_CAPTURE

Community
  • 1
  • 1
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54