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


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

我在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和user中工作并添加空间!我得到的最终输出你好用户

谢谢,您的回答将不胜感激。:)

您可以使用内爆,只需首先使用str_split即可将字符串转换为数组:

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

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

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

您可以将chunk_split()用于此目的。

$formatted = trim(chunk_split($password, 1, ' '));

这里需要trim来删除最后一个字符后的空白。

您可以使用以下代码[DEMO]:

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

chunk_split()是在PHP函数中构建的,用于将字符串分割成更小的块。

这个怎么样

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

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

这也起作用。。

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

输出:"1 b s d f 4"

    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.