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("
", "
", "");
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 "/( || )/" and nothing works. What am I doing wrong?
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("/?
|/", '</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("?
|", '</p><p>', $text);
Wait...dumb question! Should be
$text = preg_replace($new_line,'</p><p>',$text);
Sorry, I normally code in Perl and am used to the $text =~ construction.
preg_replace
is for regular expressions. What you want is a simple string replacement, so you should use str_replace
$text = $item->Body[0];
$new_line = array("
", "
", "");
$text = str_replace($new_line,'</p><p>',$text);
echo $text;