Unable to remove all line breaks from string in PHP

10,411

The problem is that you're escaping the \n for MySQL first. Try this:

<?php 
   if (isset ($_POST['comment_form_submit'])) {
    $body = $_POST['body'];

    $breaks = array("\r\n", "\n", "\r");
    $newtext = str_replace($breaks, "", $body);

    $newtext = mysql_real_escape_string($newtext);

    echo $newtext;
   }
?>

Read about the escape function you're using to see why: http://php.net/mysql_real_escape_string

Share:
10,411
DobotJr
Author by

DobotJr

Updated on June 04, 2022

Comments

  • DobotJr
    DobotJr about 2 years

    I've got a basic textarea form. What i'm trying to do is remove all line breaks from the textarea after its been submitted.

    Here's my PHP:

    <?php 
       if (isset ($_POST['comment_form_submit'])) {
        $body = mysql_real_escape_string($_POST['body']);
    
        $breaks = array("\r\n", "\n", "\r");
        $newtext = str_replace($breaks, "", $body);
    
        echo $newtext;
       }
    ?>
    

    Now let say I when filling out the form I press Shift+enter, that creates a \n in my string, but after submitting the form, $newtext still equals "\n", shouldn't "\n" be removed because I'm replacing it with ""

    Thanks.