I am printing page content from a MYSQL db in PHP. I have a text field in db called $row['description']
When storing users input into db I only use mysql_real_escape_string() so I do not edit html
Problem is I use this field from db as the html pages meta description tag. So if user inserted line breaks in description they cause a line break in the source code of the page within the meta description tag开发者_C百科. I tried to remove the line break by using a loop to skip an br formats. I use the nl2br to convert to br.
$desc_array=(explode(" ", $row['description']));
for($i=0; $i < 17;$i++){
if(nl2br($desc_array[$i])=="<br />" || nl2br($desc_array[$i])=="<br/>"){
$i++;
}
I checked my SQL file and the line breaks appear as
\r\n\r\n
I have tried to check for this format too like
$desc_array[$i])=="\r\n\r\n"
$desc_array[$i])=="\r\n"
$desc_array[$i])=="\n"
$desc_array[$i])=="\r"
but still line break gets printed in description tag. Any ideas?
$string = str_replace(array("\r", "\n"), array('', ''), $string);
I will tell you my opinion as I encountered this sitioation over and over.
Sometimes trimming out \r\n
, \n
helps, sometimes not.
In few cases i found out that i have to remove like so:
<?php
$desc = "This
is a description";
// this is just a line break [enter]
$newDesc = str_replace("
", " ", $desc); // witch outputs This is a description
?>
I never had the curiosity to find out why it doesn't want \r\n or \n, maybe i'll foind out now :)
精彩评论