Search code examples
htmlstringtrim

Remove newline from string PHP


I've been trying for the last hour to remove newlines/returns from a given string, but it just doesn't work.

I've tried:

$text = str_replace("\n", '', $text);

and

$text = trim($text, "\n");

but the output remains unchanged. Am I doing this wrong?

EDIT: Forgot to include the whole line - fixed. I have assigned the result back to the variable.

EDIT 2: Here is some more of my code:

$text = parse_bbc($row['body'], false, $row['id_msg']);
$text = preg_replace( "/\r|\n/", "", $text );
if (strlen($text) <= 300){
    echo $text . '</font></div></div>';
}else{
    $text = substr($text,0,299);
    echo $text . '</font></div></div>';
}

EDIT 3: I want this text:

This is

some very

random

dummy text

to be

This is some very random dummy text


Solution

  • Check the html of the text you are parsing - perhaps it is an issue with <br/> elements or <p></p> hidden in the content. This would mean that the solutions may not work.

    Try trim ( $text, "\n\r\x0B")

    This will remove new lines \n, carriage returns \r, and vertical tabs \x0B - the main likely culprits.