Splitting Javascript and Joining PHP

how can i write this code in PHP? I tried several things but it didn't work. Can you help me?

return s.split(/\r?\n/).join("<br>");

      

Thank!

+3


source to share


4 answers


It looks like you are using a regular expression. How about this?



echo implode(preg_split('/\r?\n/', $s), '<br>');

      

+3


source


PHP had functions split

and join

, but they are deprecated as aliases for the more widely used functions explode

and implode

. final initial version

What you are trying to do can be accomplished with implode

, explode

and str_replace

. The latter should replace any characters \r

(since they are optional). Then you can explode

use the string \n

as delimiter and implode

use again <br>

. But that would mean calling 3 functions, which is a bit overkill considering that there is only one function that does exactly what you want: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);

      



T; tr

use it nl2br

, it is that simple and it will do exactly what you want with a minimum of effort.

+2


source


I would do:

return implode("<br />", explode("\R", $s));

      

Where \R

denotes any line break, \n

or \R

or\r\n

+1


source


You can write like this:

return implode("<br />", explode("\r\n", s));

      

0


source







All Articles