问题
I have a string
$str = "101WE3P-1An Electrically-Small104TU5A-3,Signal-Interference Duplexers Gomez-GarciaRobertoTU5A-3-01"
I want to split this string by the numbers, eg:"101WE3P-1An.... "should be first element, "104TUA..." should be second element?
Somebody wrote me the following code in my previous question preg_match to match substring of three numbers consecutively? some little minutes ago:
$result = preg_split('/^\d{3}$/', $page, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
Baseline is i want to match three digited number followed by any no of capitals, followed by anything including \t ? Thanks in advance.
回答1:
You can tell preg_split()
to split at any point in the string which is followed by three digits by using a lookahead assertion.
$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 is used because the very start of the string is also a point where there are three digits, so an empty split happens here. We could alter the regex to not split at the very start of the string but that would make it a little more difficult to understand at-a-glance, whereas the flag is very clear.
回答2:
I tried match rather than split
preg_match_all('/^(\d{3}.*?)*$/', $str, $matches);
var_dump($matches);
Seems to get correct result for your sample
来源:https://stackoverflow.com/questions/14102235/splitting-string-array-based-upon-digits-in-php