Code Snippet

Home » Code Snippets » PHP » Convert BR to Newline

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);
}

Subscribe to The Thread

  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

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

  3. Ronak Damani

    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


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

      sorry the code got messed up

  4. You can also do:


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

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

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

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~