This is example with "\R" regex token which matches any unicode newline character.
"u" flag treate strings as UTF-16. Which is optional, depending on your use case.
<?php
public function nl2br($string)
{
return preg_replace('/\R/u', '<br/>', $string);
}
?>
NOTE:
preg_replace versions are much slower than using str_replace version or built-in nl2br.
Check out pcre.backtrack_limit php.ini setting for information about PCRE limit. It's good to know.
Some PHP7 benchmarks:
<?php
function nl2br_str($string) {
return str_replace(["\r\n", "\r", "\n"], '<br/>', $string);
}
function nl2br_preg_R($string)
{
return preg_replace('/\R/u', '<br/>', $string);
}
function nl2br_preg_rnnr($string)
{
return preg_replace('/(\r\n|\n|\r)/', '<br/>', $string);
}
?>
# nl2br
## Time: 0.02895712852478 s
# nl2br_str
## Time: 0.027923107147217 s
# nl2br_preg_R
## Time: 0.13350105285645 s
# nl2br_preg_rnnr
## Time: 0.14213299751282 s