【问题标题】:split the strings with space and comma and print this in a new line in php用空格和逗号分割字符串并在php的新行中打印
【发布时间】:2014-04-28 11:44:43
【问题描述】:

如果字符串长度大于33,我需要在php中根据逗号和空格来拆分字符串。

我的代码如下,用于写入文本文件

$Address="Kuruva Islands,Mananthavady Kodanad"; 

fwrite($fo, str_repeat(" ",(33-strlen($Address))/2).$Address."\r\n");

它输出像,

Palvelicham,
Mananthavady Kodanad

但我需要输出中心对齐,

             Palvelicham,Mananthavady
                     Kodanad

而且我还需要将其写入文本文件.. 请帮忙。

【问题讨论】:

  • 你为什么需要它?你在 HTML 中使用它吗?
  • 也许preg_replace('/\s+/', '/\n/', trim($string)); ?

标签: php string file replace


【解决方案1】:

您为什么要为此使用正则表达式?让它变得不必要的复杂?

$address="Palvelicham,Mananthavady Kodanad";
$replaced = str_replace(" ", "\n", $address);

输出:

Palvelicham,Mananthavady
Kodanad

【讨论】:

  • 感谢'Y U NO WORK',但这里的$address 不是静态变量,而是动态的。我还需要使用 fwrite() 将其写入文本文件。我需要它居中对齐。
【解决方案2】:

试试这个。尚未测试,但应该可以工作。

$str = 'Palvelicham,Mananthavady Kodanad';
$formated_str = implode('\r\n', explode(' ', $str));

【讨论】:

    【解决方案3】:

    使用这个函数来计算字符串的长度,并在空格和逗号之后使用explode来分割..

    function limit_text($text, $length) // Limit Text
    {
        if(strlen($text) > $length) {
        $stringCut = substr($text, 0, $length);
        $text = substr($stringCut, 0, strrpos($stringCut, ' '));
        }
        return $text;
    }
    

    展开语法:

    <?php
    $str = "Hello world. It's a beautiful day.";
    print_r (explode(" ",$str));
    ?>
    

    【讨论】:

      【解决方案4】:

      使用函数 strlen() 和 str_replace(),如下所示:

      $str = "Kuruva Islands,Mananthavady Kodanad";
      if(strlen($str) > 33) { // If the string length is greater than 33
          $str = str_replace(" ", "\n", $str); // Replace the spaces by a new line.
      }
      

      【讨论】:

        【解决方案5】:
                $result="";
                $stringinput = "Palvelicham,Mananthavady Kodanad";
                $arraystring = explode(" ", $stringinput);
                $arraystringcomma = new Array();
                foreach($arraystring as $item){
                    $arraystringcomma = array_merge(arraystringcomma , explode(",", $stringinput));
                }
                $stringoutput = new Array();
                $i= 0;
                foreach($arraystringcomma as $item){
                    if(strlen($stringoutput[$i] . $item)<=33){
                        $stringoutput[$i] .= $item;
                    }else{
                        $i++;
                        $stringoutput[$i] = $item;
                    }
                }
                $result = implode("\n",$stringoutput);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-22
          • 2014-11-10
          • 2023-03-15
          • 1970-01-01
          • 1970-01-01
          • 2023-04-04
          相关资源
          最近更新 更多