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
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, ' ');
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
)
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With