Regex formula spliting with preg_split

Viewed 19

Hello i am passing a bad moment trying to found the correct Regex formula.

$stringSplit = "+foo a -ba24+Sample3"; 

$vectorsPlus = preg_split('/[+*]/',$stringSplit ,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$vectorsMinus = preg_split('/[-*]/',$stringSplit ,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

My objetive it's get 2 diferents arrays grouping on symbol like:

$vectorsPlus [0] = '+foo';
$vectorsPlus [1] = '+Sample3';

$vectorsMinus [0] = '-ba24';

I will aprecciate any help how to solves this with the Regex magic.

1 Answers

Instead of using split, you can match the values.

Note that [+*] and [-*] both match a * char and which is not in the example data.

You can match either a + or a - followed by matching the opposite excluding whitespace chars using a negated character class.

$stringSplit = "+foo a -ba24+Sample3";

preg_match_all("/\+[^-+\s]+/", $stringSplit, $matchesPlus);
print_r($matchesPlus[0]);

preg_match_all("/-[^-+\s]+/", $stringSplit, $matchesMinus);
print_r($matchesMinus[0]);

Output

Array
(
    [0] => +foo
    [1] => +Sample3
)
Array
(
    [0] => -ba24
)

See a php demo

Related