Splitting a string array based on numbers in php?

I have a line

$str = "101WE3P-1An Electrically-Small104TU5A-3,Signal-Interference Duplexers Gomez-GarciaRobertoTU5A-3-01" 

I want to break this line into numbers, for example: "101WE3P-1An ...." should be the first element, "104TUA ..." should be the second element?

Someone wrote me the following code in my previous preg_match question to pick a substring of three numbers in a row? a few minutes ago:

 $result = preg_split('/^\d{3}$/', $page, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 

The baseline is that I want to match a three-digit number, followed by any lack of capital, followed by anything, including \ t? Thanks in advance.

-2
source share
2 answers

You can tell preg_split() to split at any point in the line followed by three digits using the lookahead statement .

 $str = "101WE3P-1An Electrically-Small104TU5A-3,Signal-Interference Duplexers Gomez-GarciaRobertoTU5A-3-01"; $result = preg_split('/(?=\d{3})/', $str, -1, PREG_SPLIT_NO_EMPTY); var_export($result); 

Gives the following array:

 array ( 0 => '101WE3P-1An Electrically-Small', 1 => '104TU5A-3,Signal-Interference Duplexers Gomez-GarciaRobertoTU5A-3-01', ) 

The PREG_SPLIT_NO_EMPTY flag PREG_SPLIT_NO_EMPTY used because the beginning of the line is also the point where there are three digits, so there is an empty division. We could change the regular expression so that it does not break at the very beginning of the line, but that would make it more difficult to understand at first glance, while the flag is very clear.

+5
source

I tried a match, not a split

 preg_match_all('/^(\d{3}.*?)*$/', $str, $matches); var_dump($matches); 

It seems to get the right result for your sample.

-1
source

All Articles