tags:

views:

318

answers:

2
+3  Q: 

PHP String Split

I need to split a string into chunks of 2,2,3,3 characters and was able to do so in Perl by using unpack:

unpack("A2A2A3A3", 'thisisloremipsum');

However the same function does not work in PHP, it gives this output:

Array
(
    [A2A3A3] => th
)

How can I do this by using unpack? I don't want to write a function for it, it should be possible with unpack but how?

Thanks in advance,

+6  A: 

Quoting the manual page of unpack :

unpack() works slightly different from Perl as the unpacked data is stored in an associative array.
To accomplish this you have to name the different format codes and separate them by a slash /.


Which means that, using something like this :

$a = unpack("A2first/A2second/A3third/A3fourth", 'thisisloremipsum');
var_dump($a);

You'll get the following output :

array
  'first' => string 'th' (length=2)
  'second' => string 'is' (length=2)
  'third' => string 'isl' (length=3)
  'fourth' => string 'ore' (length=3)
Pascal MARTIN
Thanks! I separated them by a slash but could not figure out the naming thing.print_r(unpack("A2/A2/A3/A3", 'thisisloremipsum'));as this one is not working.. it could at least create an index by itself. :/ Thanks again..
deniz
Yeah, I suppose it would be useful/helpful if it could create a numerical index by default... but that's not the way it works, so we don't have much of a choice ^^
Pascal MARTIN
A: 

I've never used this function, but according to the documentation, the A character means "SPACE-padded string". So I'd hazard a guess that it's only taking the first two characters of the first word.

Have you tried unpack("A2A2A3A3", 'this is lorem ipsum'); ?

DisgruntledGoat