2013-11-27 101 views
11

我在php中有一個字符串,名字爲$ password =「1bsdf4」;如何在php中的字符串中的每個字符後添加空格?

我想輸出「1b的小號d F 4」

這怎麼可能。我試圖破滅功能,但我沒能做到..

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

我試過這段代碼:

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

其工作並增加在招呼用戶空間! 最終輸出我得到你好用戶

謝謝你,你的答案可以理解的.. :)

+2

'$密碼= 「1bsdf4」; $ formatted = implode('',str_split($ password)); echo $ formatted;' –

回答

23

您可以使用破滅,你只需要使用str_split首先將字符串轉換到一個數組:

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

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

抱歉,沒有看到您的評論@MarkB aker如果你想將你的評論轉換爲答案,我可以刪除它。

4

您可以使用chunk_split用於此目的。

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

trim在這裏需要刪除最後一個字符後面的空格。

1

您可以使用此代碼[DEMO]

chunk_split()是內建PHP函數的字符串分割成小塊。

+0

此解決方案的唯一問題是在生成的字符串末尾添加一個額外的空間。 – suarsenegger

1

這也工作..

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

輸出:「1b的小號d F 4」

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. 
相關問題