簡體   English   中英

第 10 個逗號后的 PHP 換行符

[英]PHP newline after 10th comma

我需要拆分以下字符串:

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

假設 $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>' : '');

請查看評論以獲取解釋:-

 <?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之后的前兩行)始終是找出錯誤並解決它們的好習慣。 謝謝。

你可以用單線做到這一點。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM