-3

string

T1 - X1(1), 7
T2 - C2(-9), -15
T3 - Y2(1), 3
T5 - C2(-1), 100

regexp used for preg_split

$pattern = "/[-,#\n#()]/";
preg_split($pattern, $string);

In above regular expression it is considering the hyphen space same as minus in front of a number.

Final Result Required

array having after preg_split and trim space ["T1","X1","1","7","T2","C2","-9","-15","T3","Y2","1","3","T5","C2","-1","100"]

What changes can I make in the regexp pattern to achieve the final result required?

Ankit Jindal
  • 3,672
  • 3
  • 25
  • 37

2 Answers2

2

You should skip the negative numbers. This can be done with PCRE verbs:

-\d(*SKIP)(*FAIL)|\s*[-,#\n#()]\s*

PHP example:

$string = 'T1 - X1(1), 7
T2 - C2(-9), -15
T3 - Y2(1), 3
T5 - C2(-1), 100';
print_r(preg_split('/-\d(*SKIP)(*FAIL)|\s*[-,#\n#()]\s*/', $string, -1, PREG_SPLIT_NO_EMPTY));
  1. https://3v4l.org/m51qS
  2. https://regex101.com/r/659ocz/1/
user3783243
  • 5,368
  • 5
  • 22
  • 41
0

You could match either a whitespace character, a hyphen and a whitespace s-\s character or | match the characters you want to exclude [(),\s] using a character class:

\s-\s|[(),\s]

$data = <<<DATA
T1 - X1(1), 7
T2 - C2(-9), -15
T3 - Y2(1), 3
T5 - C2(-1), 100
DATA;

$result = preg_split("~\s-\s|[(),\s]~", $data, -1, PREG_SPLIT_NO_EMPTY);

print_r($result);

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70