简体   繁体   中英

Replace/display new line from MYSQL to PHP

I have a big problem displaying line breaks from mysql in my php generated html page. I tried out nl2br() , manual str_replace() and so on... In my sql database the record is like:

first line
second line
third line

BUT: There are no \\n 's or <br> 's in that record. If I get that data via an ajax call and using javascript: data.mystring.replace(/\\n/g, "<br />") on it, everything works fine!

But now I have to echo that data directly via php. And I don't see any line breaks. NO matter what I try. Any idea?

Here's the script (inserted via an ajax call):

$adress = mysqli_real_escape_string($con, $_POST["adress"]);
mysqli_query($con, "INSERT INTO Contact SET Adress = '$adress');

Reading the data of the database on my php page:

mysqli_query($con, "SET NAMES 'utf8'");
$query = mysqli_query($con, "SELECT * FROM Contact");
$dsatz = mysqli_fetch_assoc($query);
$newString = $dsatz["Adress"];

echo nl2br($newString);

As no \\n shown in your db you can do

UPDATE tab SET yourcommentcolumn= REPLACE(yourcommentcolumn, CHAR(13), '\\n');

the CHAR() takes an ASCII code for carrige return 13 (or you can replace it with newline with code 10 if you mean newline ) and the \\\\n is to escape the \\n.

If you manage to replace them, you can then:

echo nl2br($yourString)

You can lookup over each character and check the value of it with the ord PHP function.

Check the value against an ascii table and see what value your line separator is.

You can use str_split or access a string like an array in a loop and check each character individually.

ord documentation: http://php.net/manual/en/function.ord.php chr (contains a link to ascii table) documentation: http://php.net/manual/en/function.chr.php Strings (String access and modification by character section) documentation: http://php.net/manual/en/language.types.string.php And str_split function: http://php.net/manual/en/function.str-split.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM