Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a space after every character in a string in php?

Tags:

php

whitespace

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.. :)

like image 942
Himanshu Chawla Avatar asked Nov 27 '13 15:11

Himanshu Chawla


People also ask

How do you put a space between characters in a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').

How do you add a space in a string variable?

Use the padEnd() and padStart() methods to add spaces to the end or beginning of a string, e.g. str. padEnd(6, ' '); .

What is the use of &nbsp in PHP?

A commonly used entity in HTML is the non-breaking space:   A non-breaking space is a space that will not break into a new line. Two words separated by a non-breaking space will stick together (not break into a new line).


2 Answers

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.

like image 59
Pitchinnate Avatar answered Sep 19 '22 01:09

Pitchinnate


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.

like image 30
kero Avatar answered Sep 17 '22 01:09

kero