phpjssql
phpjssql

Reputation: 501

Get array of delimiters with preg-split

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?

Upvotes: 1

Views: 72

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

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).

Upvotes: 2

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

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

Upvotes: 0

Related Questions