note 103517 deleted from function.nl2br by googleguy
| From: | googleguy@php.net | Date: | Thu, 13 Jun 2013 11:09:06 +0000 |
| Subject: | note 103517 deleted from function.nl2br by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-195170@lists.php.net to get a copy of this message | ||
Note Submitter: matthewkastor at live dot com
----
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;
}
?>