有没有更好的方法在 PHP 中将单独的单行添加到多行?

我正在 PHP 中编写一个函数来将单行字符串分离为多行字符串。我的功能如下所示'


function addNewlines($content = null, $split_as = 25, $seprater = PHP_EOL) {

    $result = '';

    while ($content != null) {

      $result .= substr($content, 0, $split_as) . $seprater;

      $content = substr($content, $split_as);

    }

    return $result;

}

我从另一个用于将数据库数据导出到 Excel 的函数中调用这个函数,


 $detail[$value]= $this->addNewlines($detail[$value]);//call function to split

它可以为从数据库获取的所有行调用这些函数。 您可以看到,对于包含 250 个字符的字符串,addNewlines 函数可能需要 10 次迭代。有没有更好的方法来减少迭代次数或优化这个函数。我的意思是使用正则表达式或任何其他方法?


慕码人2483693
浏览 61回答 1
1回答

波斯汪

使用内置函数str_split 将行分割成块,并implode 将生成的数组与 PHP_EOL 粘合.$result = implode ( PHP_EOL , str_split( $string , 25 ) );
打开App,查看更多内容
随时随地看视频慕课网APP