Solved

# Splitting string into varying length chunks

Posted on 2011-02-16
267 Views
Hi,

I have a string e.g.

``````\$string = "123ES4GYT6889";
``````

which is always going to be the same length.

I want to split it in the same way each time - the first 3 characters, then the next 6, then the next 3.

What is the most efficient way of doing this?

Thanks,

Julian

0
Question by:DrZork101

LVL 5

Expert Comment

\$chunk1 = substr(\$str, 0, 3);
\$chunk2 = substr(\$str, 3, 6);
\$chunk3 = substr(\$str, 9, 3);
0

LVL 34

Assisted Solution

Beverley Portlock earned 250 total points
An alternative that leaves them in arrays (might be more convenient depending on what you are doing)
``````<?php

\$string = "123ES4GYT6889";
preg_match('#(.{3})(.{6})(.{3})#', \$string, \$matches );

// bits are in elements 1,2 and 3
//
print_r( \$matches );
``````

Produces

Array
(
[0] => 123ES4GYT688
[1] => 123
[2] => ES4GYT
[3] => 688
)

Lengths can be easily altered by changing the numbers in the braces, e.g. {3} to {4} and so on...
0

LVL 11

Accepted Solution

Ovid Burke earned 250 total points
I like bportlock's approach, but assuming a consistent structure to the string i would go further, and validate this as well.

``````<?php

\$string = "123ES4GYT6889";
\$a = preg_match("/([0-9]{3})([A-Z]{2}[0-9]{1}[A-Z]{3})([0-9]{3})/", \$string, \$matches);

print_r(\$matches);

?>
``````
0

## Featured Post

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and tâ€¦
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.