Reputation: 419
I am writing a function in PHP to separate single line string to multiple line string. My function is given below'
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;
}
I am calling this fucntion from an another function which used to export database data to excel,
$detail[$value]= $this->addNewlines($detail[$value]);//call function to split
which may call these function for all rows fetched from DB. You can see addNewlines function may take 10 iterations for a string contains 250 characters. is there any better way to reduce the number of iterations or optimize this function. I mean using regex or any other method?
Upvotes: 0
Views: 48
Reputation: 4157
Use the build in functions str_split
to split the line in chuncks and implode
to glue the resulting array with PHP_EOL
.
$result = implode ( PHP_EOL , str_split( $string , 25 ) );
Upvotes: 1