Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP new line every X characters in long characters sequence

Tags:

string

php

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.

like image 206
KodeFor.Me Avatar asked Dec 16 '11 18:12

KodeFor.Me


3 Answers

chunk_split($string, 10)

http://php.net/manual/en/function.chunk-split.php for more info

like image 178
Kenaniah Avatar answered Oct 12 '22 01:10

Kenaniah


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.

like image 22
fardjad Avatar answered Oct 12 '22 00:10

fardjad


<?php
$foo = '01234567890123456789012345678901234567890123456789012345678901234567890123456789';
$result = chunk_split ($foo, 10, "\r\n");
echo $result;
?>
like image 24
djot Avatar answered Oct 12 '22 01:10

djot