【问题标题】:How to add a space after every character in a string in php?如何在php中字符串的每个字符后添加一个空格?
【发布时间】:2013-12-13 08:38:54
【问题描述】:

我在 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

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

【问题讨论】:

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

标签: php whitespace


【解决方案1】:

您可以为此使用chunk_split

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

trim 在这里是必需的,以删除最后一个字符后的空格。

【讨论】:

  • 这应该是公认的答案,因为 chunk_split() 的计算时间比标记为“已接受”的 implode(str_split()) 方法减少了大约 40%。 *(使用 PHP 7.3.25 测试 3100 个案例)
【解决方案2】:

这个怎么样

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

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

【讨论】:

  • 虽然可行,但正则表达式有点慢,使用原生字符串函数的替代方法更好
【解决方案3】:

您可以使用 implode,您只需要先使用 str_split 将字符串转换为数组:

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

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

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

【讨论】:

    【解决方案4】:

    您可以使用此代码[DEMO]

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

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

    【讨论】:

    • 此解决方案的唯一问题是在生成的字符串末尾添加了一个额外的空格。
    【解决方案5】:

    这也有效..

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

    输出:“1 b s d f 4”

    【讨论】:

      【解决方案6】:
          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.
      

      【讨论】:

        猜你喜欢
        • 2014-04-17
        • 1970-01-01
        • 2014-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多