note 103517 added to function.nl2br

From: Date: Mon, 18 Apr 2011 03:49:18 +0000
Subject: note 103517 added to function.nl2br
Groups: php.notes 
Request: Send a blank email to php-notes+get-178933@lists.php.net to get a copy of this message
I was converting text to simple HTML, and converting HTML to plain text. I needed an easy function to convert line breaks, no matter if they were characters or tags, into whatever line break I required at the time. This function worked pretty well. It detects double line breaks and preserves them, as long as the line breaks are in the same format i.e. \r\n \r\n or <br> <br>. It will not preserve a double line break such as <br>\n, instead, it treats this as a single line break for obvious reasons. The following are recognized as single line breaks, and are replaced using this function: \r, \n, \r\n, <BR>, <br>, <br/>, <br />, and any combination of a single tag with any quantity of \r, \n, \r\n following it. convert_line_breaks.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; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 71.238.34.51 ---- Manual Page -- http://www.php.net/manual/en/function.nl2br.php Edit -- https://master.php.net/note/edit/103517 Del: integrated -- https://master.php.net/note/delete/103517/integrated Del: useless -- https://master.php.net/note/delete/103517/useless Del: bad code -- https://master.php.net/note/delete/103517/bad+code Del: spam -- https://master.php.net/note/delete/103517/spam Del: non-english -- https://master.php.net/note/delete/103517/non-english Del: in docs -- https://master.php.net/note/delete/103517/in+docs Del: other reasons-- https://master.php.net/note/delete/103517 Reject -- https://master.php.net/note/reject/103517 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#178933) next »