如何在php中的字符串中的每个字符后添加空格?

时间:2013-11-27 15:50:20

标签: php whitespace

我在php中有一个名为 $ password =“ 1bsdf4 ”的字符串;

我想输出“1 b s d f 4”

怎么可能。我正在尝试内爆功能,但我无法做到..

$password="1bsdf4";    
$formatted = implode(' ',$password);    
echo $formatted;

我试过这段代码:

$str=array("Hello","User");    
$formatted = implode(' ',$str);    
echo $formatted;

它在hello和用户中工作和添加空间! 最终输出我得到了 Hello用户

谢谢,你的答案将不胜感激.. :)

6 个答案:

答案 0 :(得分:33)

你可以使用implode首先需要使用str_split将字符串转换为数组:

$password="1bsdf4";    
$formatted = implode(' ',str_split($password)); 

http://www.php.net/manual/en/function.str-split.php

很抱歉没有看到您的评论@MarkBaker如果您想将评论转换为答案我可以将其删除。

答案 1 :(得分:5)

您可以将chunk_split用于此目的。

$formatted = trim( chunk_split($password, 1, ' ') );
这里需要

trim来删除最后一个字符后面的空格。

答案 2 :(得分:1)

您可以使用此代码[DEMO]

<?php
 $password="1bsdf4";
 echo chunk_split($password, 1, ' ');

chunk_split()是内置的PHP函数,用于将字符串拆分为更小的块。

答案 3 :(得分:1)

这也工作..

$password="1bsdf4";    
echo $newtext = wordwrap($password, 1, "\n", true);

输出:&#34; 1 b s d f 4&#34;

答案 4 :(得分:0)

这个怎么样

$formatted = preg_replace("/(.)/i", "\${1} ", $formatted);

根据:http://bytes.com/topic/php/answers/882781-add-whitespace-between-letters

答案 5 :(得分:0)

    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.
相关问题