Jump to content

string split loop


point86

Recommended Posts

Hi,

 

I have a string, "$string1" the contents of which is, say, "ARTWISKXJAMAKFPXIO"

 

Now I need a loop that reads through the string, and after every two characters, makes a space.

 

Thus, the resultant output will be $string1afterwards = "AR TW IS KX JA MA KF PX IO"

 

Any ideas?

 

Thanks

 

P86.

Link to comment
https://forums.phpfreaks.com/topic/42429-string-split-loop/
Share on other sites

You may be able to simplify this a little. but the basic idea is there.

 

$string1 = "ARTWISKXJAMAKFPXIO";
$newstring= "";
$i =0;
while ($i < strlen($string1))
{
//echo substr($string1, $
$newstring .= substr($string1,$i,2);
$newstring .= " ";
$i +=2 ;
echo "$i <br>";
}

echo $newstring;

Link to comment
https://forums.phpfreaks.com/topic/42429-string-split-loop/#findComment-205822
Share on other sites

<?php
$str = "ARTWISKXJAMAKFPXIO";
$result = '';
for ($i=0, $l=strlen($str); $i<$l; $i++) {
    $result .= $str{$i};
    if ($i%2) $result .= ' ';
}
echo $result;
?>

 

or (PHP5 only)

<?php
$str = "ARTWISKXJAMAKFPXIO";
$a = str_split($str, 2);
echo join (' ', $a);
?>

Link to comment
https://forums.phpfreaks.com/topic/42429-string-split-loop/#findComment-205830
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.