Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 843
Gixxy22 Avatar asked Dec 26 '22 03:12

Gixxy22


2 Answers

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, ' ');
like image 101
Tibor B. Avatar answered Dec 27 '22 17:12

Tibor B.


Try this, change $length to 1 or 3:

$string = 'test';
$length = 2;
$start = -1;

while( $start++ + $length < strlen( $string ) ) {
    $array[] = substr( $string, $start, $length );
}

print_r( $array );
/*
Array
(
    [0] => te
    [1] => es
    [2] => st
)
*/
like image 23
Danijel Avatar answered Dec 27 '22 17:12

Danijel