Reputation: 1019
I have a text field retrieved by a Solr query that contains the body of an email. I am trying to replace embedded line breaks with paragraph tags via PHP like so:
$text = $item->Body[0];
$new_line = array("\r\n", "\n", "\r");
preg_replace($new_line, '</p><p>', $text);
echo $text;
When I show the result in my IDE/debugger the newline characters are not replaced and are still there:
I have been going through threads on this site trying patterns suggested by different people including "/\s+/" and PHP_EOL and "/(\r\n|\r|\n)/" and nothing works. What am I doing wrong?
Upvotes: 2
Views: 2811
Reputation: 15629
preg_replace
is for regular expressions. You want a simple string replacement, so you should use str_replace
:
$text = $item->Body[0];
$new_line = array("\r\n", "\n", "\r");
$text = str_replace($new_line, '</p><p>', $text);
echo $text;
Upvotes: 4
Reputation: 3667
You are missing the delimiter around your regex strings and you are not assigning the value.
You can also reduce your regex:
$text = preg_replace("/\r?\n|\r/", '</p><p>', $text);
You might want switch to the multibyte safe version. They work with Unicode and you don't need delimiters there ;)
$text = mb_ereg_replace("\r?\n|\r", '</p><p>', $text);
Upvotes: 6