Splitting string array based upon digits in php? [closed]

╄→гoц情女王★ 提交于 2019-12-04 07:05:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!