how can i write this code in PHP? I tried several things but it wouldnt work. Can u help me please?
return s.split(/\r?\n/).join("<br>");
Thanks!
how can i write this code in PHP? I tried several things but it wouldnt work. Can u help me please?
return s.split(/\r?\n/).join("<br>");
Thanks!
Share Improve this question asked Jan 13, 2015 at 12:15 Björn BendigBjörn Bendig 1073 silver badges8 bronze badges 1-
2
PHP used to have
split
andjoin
functions, but they were deprecated as being aliases for the much wider usedexplode
andimplode
functions. php/split – Elias Van Ootegem Commented Jan 13, 2015 at 12:17
4 Answers
Reset to default 3It looks like you using regular expression. How about this one
echo implode(preg_split('/\r?\n/', $s), '<br>');
PHP used to have split
and join
functions, but they were deprecated as being aliases for the much wider used explode
and implode
functions. RTM
What you're trying to do can be done using implode
, explode
, and str_replace
. The latter should replace any \r
characters (seeing as they're optional). You then can explode
the string using \n
as delimiter, and implode
it again using <br>
. But that would mean calling 3 functions, which is a bit redundant considering there is a single function that does exactly what you need: nl2br
return implode(
'<br/>',
//split on \n
explode(
"\n",
//remove any \r chars
str_replace(
"\r",
'',
$s
)
)
);
//The results are the same as this clean, simple one-liner
return nl2br($s);
Tl;tr
use nl2br
, it's as simple as that, and it'll do exactly what you want, with the least amount of effort required.
I'd do:
return implode("<br />", explode("\R", $s));
Where \R
stands for any line break, \n
or \r
or \r\n
You can write like this :
return implode("<br />", explode("\r\n", s));