-2

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.

Community
  • 1
  • 1
Aditya
  • 4,453
  • 3
  • 28
  • 39

2 Answers2

5

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.

salathe
  • 51,324
  • 12
  • 104
  • 132
  • Nice one, can you tell me why you used var_export? – Aditya Dec 31 '12 at 13:51
  • @Aditya to show you the resulting array, no other reason. – salathe Dec 31 '12 at 13:51
  • But there seems to be a problem with a bigger string that im taking from a text file! – Aditya Dec 31 '12 at 13:56
  • Oh noes! How about asking a new question detailing your "problem" (in the form of a question) with reference to that "bigger string"? Comments aren't the place to bounce back and forth support questions (try chat). – salathe Dec 31 '12 at 13:58
  • Ok..simple i want to match three digited number follwed by a capital letter followed by anything(including a \t)? :) – Aditya Dec 31 '12 at 14:06
  • I want a pony and a plastic rocket. However, here is not the right place for either of us to be sharing what we *want*. – salathe Dec 31 '12 at 14:14
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/21956/discussion-between-aditya-and-salathe) – Aditya Dec 31 '12 at 14:28
-1

I tried match rather than split

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

Seems to get correct result for your sample

user1938139
  • 141
  • 1
  • 5