changing new line to <br> in text area
Asked Answered
S

2

8

My problem is pretty simple. I want to change new lines in text area to <br> tags BUT I need the final string to be one-line text. I tried using nl2br function but as a result I get string with <br> tags and new lines. I also tried to simply replace &#013 or &#010 symbols with <br> using str_replace but it doesn't work.
Here is sample of my latest code:

Godziny otwarcia: <textarea name="open" rows="3" cols="20">'."$openh".'</textarea>
<input type="submit" name="openb" value="Zmień"/><br>


    if($_POST['openb']) {
    $open = $_POST['open'];
    str_replace('&#010', '<br>', $open);
    change_data(21, $open);
}

The $openh is result of this:

$tab = explode('<br>', $openh);
$openh = null;
for($i=0;$i<count($tab);$i++)
    $openh = $openh . $tab[$i] . '&#013';

(yes, I know i could use str_replace, don't ask why I did it this way)
and the original $openh is $openh = 'Pon-pt 9:00-17:00<br>Środa 12:00-17:00'

Also you may want to see my change_data function as it is connected to why i need the string to be in one line, so here it is:

function change_data($des_line, $data) {
    $file = 'config.php';
    $lines = file($file);
    $i=1;
    foreach($lines as $line_num => $line) {
        $wiersz[$i] = $line;
        $i++;
    }
    $change = explode("'", $wiersz[$des_line]);
    $wiersz[$des_line] = $change[0] . "'" . $data . "'" . $change[2];
    $i = 1;
    $f = fopen($file, w);
    while($i <= count($wiersz)) {
        fwrite($f, $wiersz[$i]);
        $i++;
    }
    fclose($f);
    header('location: index.php?p=admin');
}

I'm not PHP specialist so sometimes I do things little "hard" way.. I had huge problems with reading file config.php line by line and these are results of my few-hours effort :(

Sitka answered 12/10, 2013 at 9:12 Comment(0)
L
21

have you tried the php constant PHP_EOL? in you str_replace code?

$open=str_replace(PHP_EOL,"<br>",$_POST["open"]);
Loculus answered 12/10, 2013 at 9:26 Comment(1)
I didn't try it but I managed to do it with "\n" .. It just needed " instead of ' And all of this because my browser didn't load the whole page in PHP Manual last time.. Now I reopened page and there were some good examples of nl2br function and how does it workSitka
S
5

There is a ready made PHP function for that named nl2br

Source: https://mcmap.net/q/1322094/-how-to-replace-all-new-lines-of-string-with-lt-br-gt-in-php

Sidedress answered 27/1, 2021 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.