tags:

views:

390

answers:

5

I'd like to get a string, for example 'sdasdasdsdkjsdkdjbskdbvksdbfksjdbfkdbfksdjbf' and split that up every six charaters.

I don't think explode or strtok will work for that?

Any ideas?

+1  A: 

You want chunk_split()

dnagirl
+3  A: 

See the docs on str_split.

Paul Lammertsma
+7  A: 

str_split was designed for just that.

$str = "sdasdasdsdkjsdkdjbskdbvksdbfksjdbfkdbfksdjbf";
$parts = str_split($str, 6);
print_r($parts);
Marek Karbarz
Brilliant, thanks Marek!
logic-unit
A: 
$str = 'abcdefghijklmnopqrstuvwxyz';
$i = 0; $len = 6; $bits = array();
while($i < strlen($str)) {
    $bits[] = substr($str, $i, $len);
    $i += $len;
}

Edit: or use str_split as suggested (php has too many functions built in ffs!)

Rob
And people are too happy to reinvent the wheel :)
Ben James
But the wheel is an extremely useful tool that we would be hard pressed to live without. I wonder how much overhead these thousands of rarely used functions cost. I came across the function date_sunrise() in the manual the other day, come on that's ridiculous!
Rob
Because 6 lines of dense PHP code are less overhead than a single function that takes up only a few bytes in compiled form...? :) Sure, it doesn't make sense to include a function for **everything**, but both `str_split` and `date_sunrise` are sufficiently complex to warrant it, and are (quite apparently) getting used every once in a while. `date_sunrise` maybe not that often, but when you do need it, you'll be thankful somebody did the work already.
deceze
A: 

Not the cleanest way but it works.

<?php
$MyString = 'asdfasdlkfjasdlkfjasdlkfjasldkfj';
$MyNewString;
$n = 6; // How many you want before seperation
$MyNewString = substr($MyString,0,$n); 
$i = $n;
while ($i < strlen($MyString)) {
        $MyNewString .= '-'; // Seperator Character
        $MyNewString .= substr($MyString,$i,$n);
        $i = $i + $n;
}
echo $MyNewString
?>
Nick