There is already a function in PHP that converts a new line to a br called nl2br()
. However, the reverse is not true. Instead you can create your own function like this:
function br2nl($string)
{
$breaks = array("<br />","<br>","<br/>");
return str_ireplace($breaks, "\r\n", $string);
}
Then whenever you want to use it, just call it as follows:
$original_string = 'some text with<br>tags here.';
$good_string = br2nl($original_string);
There are three things worth mentioning:
- It may be better to store the data in the database exactly as the user entered it and then do the conversion when you retrieve it. Of course this depends what you are doing.
- Some systems such as Windows use \r\n. Some systems such as Linux and Mac use \n. Some systems such as older Mac systems user \r for new line characters. Given this and especially if you choose to use point 1. above, you might prefer to use the PHP constant
PHP_EOL
instead of \r\n. This will give the correct new line character no matter what system you are on.
- The method I posted above will be more efficient than preg_replace. However, it does not take into account non-standard HTML such as
<br />
and other variations. If you need to take into account these variations then you should use the preg_replace()
function. With that said, one can overthink all the possible variations and yet still not account for them all. For example, consider <br id="mybreak">
and many other combinations of attributes and white space.