Skip to content
Advertisement

Split string into 2 letters

I am trying to split a string into 1, 2 and 3 segments.

For example, i currently have this:

$str = 'test';
$arr1 = str_split($str);

foreach($arr1 as $ar1) {
    echo strtolower($ar1).' ';
}

Which works well on 1 character splitting, I get:

t e s t 

However when I try:

$arr2 = str_split($str, 2);

I get:

te st

Is there a way so that I can output this? :

te es st

and then also with 3 characters like this?

tes est

Advertisement

Answer

Here it is:

function SplitStringInWeirdWay($string, $num) {
    for ($i = 0; $i < strlen($string)-$num+1; $i++) {
        $result[] = substr($string, $i, $num);
    }
    return $result;
}

$string = "aeioubcdfghjkl";

$array = SplitStringInWeirdWay($string, 4);

echo "<pre>";
print_r($array);
echo "</pre>";

PHPFiddle Link: http://phpfiddle.org/main/code/1bvp-pyk9

And after that, you can just simply echo it in one line, like:

echo implode($array, ' ');
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement