第 10 个逗号后的 PHP 换行符

  • 本文关键字:PHP 换行符 php
  • 更新时间 :
  • 英文 :


我需要拆分以下字符串:

333 ,351 ,359 ,360 ,370 ,371 ,385 ,492 ,512 ,514 ,528 ,539 ,546 ,628 ,630 ,634 ,636 ,702 ,706 ,709 ,710 ,715 ,718 ,719 ,763 ,770 ,803 ,822 ,823

进入单独的行,在最后一个 10 个逗号之后开始新行,这有什么意义吗?

所以它看起来像这样:

333 ,351 ,359 ,360 ,370 ,371 ,385 ,492 ,512 ,514 ,
528 ,539 ,546 ,628 ,630 ,634 ,636 ,702 ,706 ,709 ,
710 ,715 ,718 ,719 ,763 ,770 ,803 ,822 ,823

请检查评论以获取解释:-

 <?php
    error_reporting(E_ALL); // check if any error occur
    ini_set('display_errors',1); // display error
    $string = '333 ,351 ,359 ,360 ,370 ,371 ,385 ,492 ,512 ,514 ,528 ,539 ,546 ,628 ,630 ,634 ,636 ,702 ,706 ,709 ,710 ,715 ,718 ,719 ,763 ,770 ,803 ,822 ,823'; // original string
    echo $string; // echo original string
    $array = explode(',',$string); // explode string with comma to make it array
    echo "<pre/>";print_r($array); // print array
    $chunked_array = array_chunk($array,10); // chunk array to each 10 counts and make a multidimensional array
    $new_string = ''; // create a new empty string
    foreach ($chunked_array as $chunked_ar){ // iterate through multi-dimensional array 
      $new_string .= implode(',',$chunked_ar)."n"; // convert each array to string and add new line and assign it to new string variable
    }
    echo $new_string; // echo new variable.
  ?>

输出:- https://eval.in/557389

注意:添加error_reporting代码(<?php后前两行)始终是找出错误并解决它们的好习惯。谢谢。

假设$string是你的前一个字符串:

<?php
$myArray = explode(",", $string);
$newString = "";
$count = 0;
foreach ($myArray as $value)
{
  $newString = $newString.$value.",";
  $count++;
  if ($count==10)
  {
    $count=0;
    $newString = $newString."n";
  }
}
?>

这将做到这一点...

$str = '333 ,351 ,359 ,360 ,370 ,371 ,385 ,492 ,512 ,514 ,528 ,539 ,546 ,628 ,630 ,634 ,636 ,702 ,706 ,709 ,710 ,715 ,718 ,719 ,763 ,770 ,803 ,822 ,823';
$iCount = 0;
foreach (explode(',',$str) as $iNum)
    echo $iNum.' ,'.(++$iCount % 10 == 0 ? '<br>' : '');

你可以用单行来做到这一点。

preg_replace('/((.*?,){10})/', "$1n", $text);

最新更新