Reputation: 223
I have a string in php named $password="1bsdf4";
I want output "1 b s d f 4"
How is it possible. I was trying implode function but i was not able to do..
$password="1bsdf4";
$formatted = implode(' ',$password);
echo $formatted;
I tried this code:
$str=array("Hello","User");
$formatted = implode(' ',$str);
echo $formatted;
Its working and adding space in hello and user ! Final Output I got Hello User
Thanks, yours answers will be appreciated.. :)
Upvotes: 21
Views: 46892
Reputation: 10638
You can use chunk_split()
for this purpose.
$formatted = trim(chunk_split($password, 1, ' '));
trim
is necessary here to remove the whitespace after the last character.
Upvotes: 11
Reputation: 1
function break_string($string, $group = 1, $delimeter = ' ', $reverse = true){
$string_length = strlen($string);
$new_string = [];
while($string_length > 0){
if($reverse) {
array_unshift($new_string, substr($string, $group*(-1)));
}else{
array_unshift($new_string, substr($string, $group));
}
$string = substr($string, 0, ($string_length - $group));
$string_length = $string_length - $group;
}
$result = '';
foreach($new_string as $substr){
$result.= $substr.$delimeter;
}
return trim($result, " ");
}
$password="1bsdf4";
$result1 = break_string($password);
echo $result1;
Output: 1 b s d f 4;
$result2 = break_string($password, 2);
echo $result2;
Output: 1b sd f4.
Upvotes: 0
Reputation: 223
This also Worked..
$password="1bsdf4";
echo $newtext = wordwrap($password, 1, "\n", true);
Output: "1 b s d f 4"
Upvotes: 0
Reputation: 954
You can use this code [DEMO]:
<?php
$password="1bsdf4";
echo chunk_split($password, 1, ' ');
chunk_split() is build-in PHP function for splitting string into smaller chunks.
Upvotes: 1
Reputation: 7556
You can use implode you just need to use str_split first which converts the string to an array:
$password="1bsdf4";
$formatted = implode(' ',str_split($password));
http://www.php.net/manual/en/function.str-split.php
Sorry didn't see your comment @MarkBaker if you want to convert you comment to an answer I can remove this.
Upvotes: 43
Reputation: 1142
How about this one
$formatted = preg_replace("/(.)/i", "\${1} ", $formatted);
according to: http://bytes.com/topic/php/answers/882781-add-whitespace-between-letters
Upvotes: 0