Reputation: 13511
How can I add a new line characters (\n\r) in txt file every 10 characters?
What I have is a long sequence of characters, and I like to create a new line for each 10 characters.
in example, let's say I have that sequence of characters:
FadE4fh73d4F3fab5FnF4fbTKhuS591F60b55hsE
and I like to convert it to that:
FadE4fh73d
4F3fab5FnF
4fbTKhuS59
1F60b55hsE
How can I do that ?
I know that I can use a loop for that, but because the above string is an example and my string that I have to split it is really very very long, just I wander if there is any faster and more easy way to spit my string.
Upvotes: 13
Views: 18901
Reputation: 880
As mentioned above, the use of chunk_split()
might have unwanted consequences, as the break sequence is always added to the end once again.
You can instead use a combination of str_split()
and implode()
to first split the string every X characters and then recombine it with a break sequence. By using implode()
, the break sequence will not be added to the end, again.
I've build a helper function who does this for me after 75 chars:
function createFold($s, $b = '\\n ') {
$chunks = str_split($s, 75);
return implode($b, $chunks);
}
Upvotes: 0
Reputation: 20404
using chunk_split()
:
$str = chunk_split($str, 10, "\n\r");
or using this regex:
$str = preg_replace("/(.{10})/", "$1\n\r", $str);
And by the way did you mean \r\n
(New line in Windows environment) by \n\r
?
if so then the third argument for chunk_split()
can be omitted.
Upvotes: 7
Reputation: 7
<b><</b>?<b>php</b><br/>
$body=$row['details'];<br/>
$str = chunk_split($body, 14, "<b><</b><b>br</b><b>/</b>");<br/>
echo $str;<br/>
?
Upvotes: -1
Reputation: 2947
<?php
$foo = '01234567890123456789012345678901234567890123456789012345678901234567890123456789';
$result = chunk_split ($foo, 10, "\r\n");
echo $result;
?>
Upvotes: 2
Reputation: 5201
chunk_split($string, 10)
http://php.net/manual/en/function.chunk-split.php for more info
Upvotes: 39