Search code examples
phpnl2br

nl2br and str_replace not working in PHP script


I am saving and editing data in text files through a text area using CKeditor and everything is working smoothly. Everything except new lines ("<br />") that don't show when I try to edit/update the text file via my update.php. I really can't find out what is the issue, I have tried to replace tag after tag and did not manage to solve the problem.

Code for reading and writing on the text file:

$text1 = "../conteudos/start/text1.txt";
if (isset($_POST['body1'])) {
    $newData = nl2br($_POST['body1']);
    $handle = fopen($text1, "w");
    fwrite($handle, $newData);
    fclose($handle);
}
// ------------------------------------------------
if (file_exists($text1)) {

    $myData1 = file_get_contents($text1);
    $myData1 = strip_tags($myData1);
}

Code for editing the text contents:

<textarea class="ckeditor" name="body1" id="body1">
    <?php echo str_replace("<br />","",$myData1); ?>
</textarea>

As mentioned before, the text shows up nicely on my index.php with no html tags whatsoever, but when I try to edit it via the text area above I still get no tags, but I get all the text into one single line. This really should be working because I am using "nl2br" function, but apparently something is canceling it.

What can I do?


Solution

  • Something very strange happened because according to the user Touch, his method was working on his computer. Unfortunately it wasn't working on mine! So after a while thinking I came to the conclusion that I was over doing some process of replacement of tags. In order to confirm or not this theory of mine I decided do "back-engineer" Touch's method by erasing line by line and seeing what the result was. In the end I saw that my conclusion was correct, I was over doing process of tag replacement because this code:

    $text2 = "../conteudos/start/text2.txt";
    if (isset($_POST['body2'])) {
        $newData = nl2br($_POST['body2']);
        $handle = fopen($text2, "w");
        fwrite($handle, $newData);
        fclose($handle);
    }
    // ------------------------------------------------
    if (file_exists($text2)) {
    
        $myData2 = file_get_contents($text2);
        $myData2 =  $myData2;
    }
    

    worked in perfection. I can only think that this was due to I was using KCEditor...

    A big thanks to all that answered, maing me think and helping me this way to achieve my goal!