Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Convert BR to Newline

Technique #1

function br2newline( $input ) {
     $out = str_replace( "<br>", "\n", $input );
     $out = str_replace( "<br/>", "\n", $out );
     $out = str_replace( "<br />", "\n", $out );
     $out = str_replace( "<BR>", "\n", $out );
     $out = str_replace( "<BR/>", "\n", $out );
     $out = str_replace( "<BR />", "\n", $out );
     return $out;

Converts a break tag to a newline - no matter what kind of HTML is being processed.

Technique #2

function br2nl( $input ) {
 return preg_replace('/<br(\s+)?\/?>/i', "\n", $input);


  1. Technique #2 will work a lot better than #1
    But in #1, you could just use the first three calls and use str_ireplace() instead.

  2. Vicky
    Permalink to comment#

    I’m suffered a lot. A used ” but I should use ‘. Could it be really a mistake?

  3. Ronak Damani
    Permalink to comment#

    please help me out why is “i” used in
    function br2nl( $input ) {
    return preg_replace(‘//i’, “\n”, $input);

    at the end of first parameter of preg_ replace

    • Ronak Damani
      Permalink to comment#

      function br2nl( $input ) {
      return preg_replace('//i', "\n", $input);

      sorry the code got messed up

  4. Permalink to comment#

    You can also do:

    function _br2nl($input)
    return str_replace(array("", "", "", "", "", ""),"\n", $input );

    • Permalink to comment#

      function _br2nl($input)
      return str_replace(array(“<br>”, “<BR>”, “<br/>”, “<BR/>”, “<br />”, “<BR />”),”\n”, $input );

      function _br2nl($input)
      return str_replace(array('', '', ''),'\n', strtolower($input) );
  5. Permalink to comment#

    `(\s+)?` could just be `\s*`.

  6. It seems that you just need to use the nl2br() function

    thats all.

  7. You can replace this:


    With this:


    Here is how I would do it:

    preg_replace('/<br\s*\/?>/i', "\n", $input)

    But you should know that it won’t work on malicious input, such as:

    <br onmouseover="alert('pwnd')" />

    Here is a test of such input.

  8. atinder pal singh

    is there any way to apply css style to br

  9. biju
    Permalink to comment#

    this is help full. but i want to change in wordpress to . i tried remove_filter( ‘the_content’, ‘wpautop’ );
    remove_filter( ‘the_excerpt’, ‘wpautop’ ); but not work

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";