Split string into 2 letters

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

For example, I have this:

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

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

Which works well when splitting 1 character, I get:

t e s t 

However, when I try:

$arr2 = str_split($str, 2);

I get:

te st

Is there any way that I can output this?

te es st

and then also with 3 characters like this?

tes est
+4
source share
5 answers

There he 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 simply just echo on a single line, for example:

echo implode($array, ' ');
+5
source

Try this, change $lengthto 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
)
*/
+2
source

$string{0} $string{1} $string{n}

, !

, strlen

$length = strlen($string);

for($i = 0; $i < $length; ++$i){
    // Your job
}

$i, $i - 1, $i + 1, .

+1

, chunk_split:

$str = "testgapstring";
$res = chunk_split($str, 3, ' ');

echo $res; // 'tes tga pst rin g '

but you have an extra space character at the end, also if you need it to be an array, something will work:

$chunked = chunk_split($str, 3, ' ');
$arr = explode(' ', rtrim($chunked));

Another example:

echo $chunked = rtrim(chunk_split('test', 2, ' ')); // 'te st'
+1
source
<?php 

function my_split($string, $count){

    if(strlen($string) <= $count){
        return $string;
    }

    $my_string = "";
    for($i; $i< strlen($string) - $count + 1; $i++){
        $my_string .=  substr($string, $i, $count). ' ';
    }

    return trim($my_string);
}

echo my_split('test', 3);

?>

And there will be "tes est"

+1
source

All Articles