Forum Moderators: coopster

Message Too Old, No Replies

Insert a space after x characters

How to stick a space into a string

         

proper_bo

11:29 am on Dec 21, 2005 (gmt 0)

10+ Year Member




I have a string and I would like to insert a space after x characters. I have looked but I can't seem to find the code to do this. The only way I could see would be to split the string then stick it together again with a space in the middle. There has to be a better way?

tomda

12:03 pm on Dec 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just did this on the fly so it has not been tested for special cases (like if string_lenght is equal to 0, etc.)

Give it a try... I used arrays and substr.
May be someone else has a better solution?

<?php
// YOUR TEXT
$txt="merrychrisdetmastdeoeferthtyhtallmyfriendsandedefamddedeewewily";

//EMPTY ARRAY
$txt_array=array();

// GET STRING LENGHT
$len=strlen($txt);

// WANT TO ADD SPACE AFTER X CHARACTER
$number="5"; // here, 5 character

//COUNT FOR LOOP BELOW
$count=$len/$number;

//SHOW SOME RESULT
echo 'CALCUL: '.$len.'/'.$number.'='.$count.'<br><br>';

//LOOP
$i="0";
while($i<=$count) {
if($i=="0") {$ib="0";} else {$ib=($i*$number)+1;}
$txt_array[$i]=substr($txt,$ib,5);
$i++;}

//PRINT ARRAY
print_r ($txt_array);

//GET FINAL TEXT
$count_array=count($txt_array)-1; $i="0";
while ($i<=$count_array) {
if ($i=="0") {$txt=$txt_array[$i].' '; } else {$txt .=''.$txt_array[$i].' ';}
$i++;}

echo '<br><br><b>RESULT</b><br>'.$txt.'';
?>

proper_bo

12:15 pm on Dec 21, 2005 (gmt 0)

10+ Year Member



So you have split it and then stuck it back together?

I actually only want to stick one space into a string rather than several, but your code could be used for either.

Thank you. I will have a go later.

tomda

12:26 pm on Dec 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



So you have split it and then stuck it back together?

Yeah, this is what I did!

I actually only want to stick one space into a string rather than several, but your code could be used for either.

Sorry, I though you wanted to add EVERY x character...