2013-11-27 10 views
11

私は$ password = "1bsdf4"という名前のPHPの文字列を持っています。PHPの文字列内のすべての文字の後にスペースを追加するには?

私はそれが可能であるどのように出力"1件のB S DのF 4"

をしたいです。その作業

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

とハローとユーザーにスペースを追加:私はこのコードを試してみました

$password="1bsdf4";  
$formatted = implode(' ',$password);  
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を見ませんでしたあなたがあなたが答えにコメントを変換したいのであれば、これを取り除くことができます。

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); 

出力:"1件のB S 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. 
関連する問題