point86 Posted March 12, 2007 Share Posted March 12, 2007 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 More sharing options...
peeps Posted March 12, 2007 Share Posted March 12, 2007 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 More sharing options...
Barand Posted March 12, 2007 Share Posted March 12, 2007 <?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 More sharing options...
point86 Posted March 16, 2007 Author Share Posted March 16, 2007 Ok thanks, this works fine: I've split the string successfully. Now if the string was made up of ASCII characters (eg 66 67 68 69), how do I get the system to convert these into normal character values (eg B C D E)? Thanks P86. Link to comment https://forums.phpfreaks.com/topic/42429-string-split-loop/#findComment-208524 Share on other sites More sharing options...
peeps Posted March 16, 2007 Share Posted March 16, 2007 Give these two functions a try. printf("%c%c%c%c", 66, 67, 68, 69); //or $var = chr(66); Hope that helped. Link to comment https://forums.phpfreaks.com/topic/42429-string-split-loop/#findComment-208528 Share on other sites More sharing options...
point86 Posted March 16, 2007 Author Share Posted March 16, 2007 Thanks, that's fantastic Point. Link to comment https://forums.phpfreaks.com/topic/42429-string-split-loop/#findComment-208874 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.