0

When converting new line characters to HTML break (<br>)

What is Cleaner to use?

str_replace(array("\r\n", "[br]", "\r"), '<br>', $Content);

OR

str_replace("\r\n", '<br>', $Content);
str_replace("[br]", '<br>', $Content);
str_replace("\r", '<br>', $Content);

I've been using the first method, but a friend of mine said that the way I currently use is more sloppy in terms of processing.

I'm using the formatting in a function; so

function Formatting ($Content)
{
 $Content = str_replace(array("\r\n", "[br]", "\r"), '<br>', $Content);
 return $Content;
}
5
  • The second way is probably faster, but only by some microseconds even if that. Use whichever approach you will find easier to understand for when you (or your acquaintances) maintain the code. Commented Nov 28, 2012 at 3:07
  • what about "\n" ? the user notes on the nl2br() have some fine examples of covering all the possibilities. Commented Nov 28, 2012 at 3:08
  • @Vulcan So in terms of processing, we're talking about time which isn't any substantial amount Commented Nov 28, 2012 at 3:10
  • @Dagon I quickly typed this up to give the people viewing the idea of what I am doing Commented Nov 28, 2012 at 3:11
  • type slower, we only know what you type, don't make people helping you for free have to guess Commented Nov 28, 2012 at 3:14

2 Answers 2

1

I would tweak this one myself (from the user notes in the manual page http://php.net/manual/en/function.nl2br.php:

<?php
/**
 * Converts newlines and break tags to an
 * arbitrary string selected by the user,
 * defaults to PHP_EOL.
 *
 * In the case where a break tag is followed by
 * any amount of whitespace, including \r and \n,
 * the tag and the whitespace will be converted
 * to a single instance of the line break argument.
 *
 * @author Matthew Kastor
 * @param string $string
 *   string in which newlines and break tags will be replaced
 * @param string $line_break
 *   replacement string for newlines and break tags
 * @return string
 *   Returns the original string with newlines and break tags
 *   converted
 */
function convert_line_breaks($string, $line_break=PHP_EOL) {
    $patterns = array(   
                        "/(<br>|<br \/>|<br\/>)\s*/i",
                        "/(\r\n|\r|\n)/"
    );
    $replacements = array(   
                            PHP_EOL,
                            $line_break
    );
    $string = preg_replace($patterns, $replacements, $string);
    return $string;
}
?>
Sign up to request clarification or add additional context in comments.

Comments

0

In Response to Dagons comment, his suggestion worked perfectly; no need to create a new function to do this task by using nl2br()

http://php.net/manual/en/function.nl2br.php

1 Comment

well you do to replace [br]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.