admin管理员组文章数量:1355748
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));
本文标签: Javascript split and join in PHPStack Overflow
版权声明:本文标题:Javascript split and join in PHP - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744029837a2578700.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论