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

Comments

  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#

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

    • 
      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:

    (\s+)?
    

    With this:

    \s*
    

    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

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".