I would like to use the text-indent property (or something like this) to add a indentation of the first line of each paragraph.
First the user can write his text in a textarea, then save it in a DB.
When I want to display this text i use :
$exhib = $res->fetch_array();
echo "<div class='infoContent'>". nl2br($exhib['description']) . "</p></div>";
The line return of the user are stored as \n in DB, and modified to <br /> by nl2br. With my CSS :
.infoContent
{
text-indent: 10px;
}
only the first line is indented. (normal behavior).
Q : How can I make this indentation automatic for each line after a <br /> tag ?
I tried a ugly solution, but it doesn't work because empty paragraph section <p></p> doesn't create another line return (in case the user enter 2 line return \n\n).
echo "<div class='infoContent'><p>" . str_replace("<br />", "</p><p>", nl2br($exhib['description'])) . "</p></div>";
I can replace <p></p> tag by <br /> but it seems to be a very bad solution...
EDIT:
JSfiddle
Thanks
\n\n usually means a new paragraph (enter). The white space between paragraphs is CSS and is actually default browser styling (1em I think?). \n is a <br> (shift + enter).
So don't use nl2br() and do it yourself:
$text = '<p>' . htmlspecialchars($text) . '</p>'; // HTML ENCODE!
$text = preg_replace('#\n\n\n*#', '</p><p>', $text); // 2 or more \n
$text = preg_replace('#\n#', '<br />', $text); // all left-over \n
$text = preg_replace('#><#', ">\n<", $text); // if you like </p>\n<p> with a newline between, like I do
http://3v4l.org/b0AhL
This is pretty much what Markdown does (and Textile and those): 1 newline = BR (not exactly in Markdown) and 2 newlines = P. I always use simple Markdown for rendering plain text.
When you submit your textarea, instead of using CSS to indent only the first line, you can use (non-breaking space).
when you submit your text area, I assume you grab it as such:
$userText = $_POST['description']
Well, before you submit to your database, you could use a simple replace - After you grab the text:
$userText = str_replace("\n", "\n ", $userText);
Then submit that to the database. When it comes back, the nl2br will still make the \n into a <br /> and then it won't see the , though the HTML will see them as four spaces (equal to an indent).
It's dirty, but simple!
Reference: http://www.w3schools.com/php/func_string_str_replace.asp
Related
I am creating a post_blog.php file where user will enter all fields one by one like post_title, post_author etc.
When user write post_text which contains many paragraphs and i get that text by using post method in php it displays me all value in plain text . it do not contain any paragraphs etc.
Here is the code :
<textarea rows="400" cols="100" name="post_text">
Enter post text here .. upto 5000 characters .
</textarea>
in php :
if()....
echo $post_text = $_POST['post_text'];
Demo Input in post_text:
Enter post text here
.. upto
5000
characters .
OUTPUT:
Enter post text here .. upto 5000 characters .
Expected OUTPUT :
Enter post text here
.. upto
5000
characters .
Your problem isn't in the php; Your problem is that HTML doesn't accept white spaces (line breaks, sapces, etc.) and display them as one space. There are some solutions:
Use the <pre> tag, which shows the text as-is:
<?php
...
echo '<pre>' . $post_text = $_POST['post_text'] . '</pre>';
Use the CSS white-space: pre; definition, which is excatly like the <pre> tag, except that it's can be applied to any element, and you cannot style a <pre> tag:
<?php
...
echo '<div style="white-space: pre;">' . $post_text = $_POST['post_text'] . '</div>';
See MDN Docs about CSS' white-space declaration.
The last solution is to replace any line break with the <br> tag and any space with :
<?php
...
echo $post_text = str_replace(' ', ' ', str_replace('\n', '<br>', $_POST['post_text']));
When user press Enter, line break \n inserted in string but in html doesn't show. You should convert it to <br> to showing in html. The str_replace() can replace it in string.
$newStr = str_replace("\n", "<br>", $str)
Also you can use native function nl2br() that inserts HTML line breaks before all newlines in string as #VictorFedorenko mentioned in comment
$newStr = nl2br($str)
I have read this post that discuss about converting html break tag into a new line in php. Other people said it's work for them but something weird happened to me.
this is the code I use:
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);`
and this is the code they use :
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
both insert "\r\n" into the text , why is this happening ?
screenshot:
if there's any previous post / PHP method let me know
EDIT : adding my code that echo the textbox
<-- THIS WONT WORK -->
$username = $_SESSION['username'];
$unsafenomorsoal = $_POST['nomorsoal'];
$unsafejawaban = $_POST['jawaban'];
$nomorsoal = mysqli_real_escape_string($konek,$unsafenomorsoal);
$jawabannotcut = substr($unsafejawaban,0,50000);
$unsafejawabanfirst = nl2br($jawabannotcut);
$jawaban1 = mysqli_real_escape_string($konek,$unsafejawabanfirst);
$breaks = array("<br />","<br>","<br/>");
$jawaban = str_ireplace($breaks, PHP_EOL, $jawaban1);
$_SESSION['textvaluejawaban'] = $jawaban;
and this is what echoed :
echo "<div class=\"head-main-recent-background\" style=\"background:white;width:99%;color:black;text-align:left;height:1000px;position:relative;top:130px;margin-top:10px;\">- Jawab Soal -<br/>".$jawabanerror."<br/>Nama : ".$_SESSION['username']."<br/>
<form method=\"post\" action=\"prosesjawabsoal.php\">
<input type=\"hidden\" name=\"nomorsoal\" value=\"".$_SESSION['nomorsoal']."\"/>
Jawaban : <br/>
<textarea placeholder=\"Max 40.000 Huruf\" style=\"overflow- x:none;width:99%;height:300px;\" type=\"text\" name=\"jawaban\" maxlength=\"40000\" >".$_SESSION['textvaluejawaban']."</textarea>
<br/>Captcha <br/>
<div style=\"overflow:hidden;\" class=\"g-recaptcha\" data- sitekey=\"6LfYQicTAAAAAFstkQsUDVgQ60x_93obnKAMKIM9\"></div><br/>
<button type=\"submit\" name=\"submit\" style=\"margin-top:10px;height:auto;width:auto;\">Kirim Jawaban</button>
</form>
</div>";
Note : The snippet won't work because it's php
Sorry i used snippet due to error while posting the code !
EDIT :
tried preg_replace() method but still same result
EDIT :
change title to tell that preg_replace not work
Your problem is the mysqli_real_escape_string(). The converts the "\r\n" into a string to make it safe to input into the database. Remove it completely. Instead use htmlspecialchars when you output to screen:
echo htmlspecialchars($myUnsafeVar);
Apply these rules (as a starting point, there's always possible exceptions, but in rare cases):
use mysqli_real_escape_string when inputting strings into a database. It won't do what you expect when outputting to screen - so anything that has been mysql escaped() should not appear on screen.
use htmlspecialchars (which you don't have!) when outputting to screen.
use url_encode for adding stuff into a URL
There are also many different "escape" function (e.g. inserting into JSON, inserting into mysql, inserting into other databases). Use the right one for what you need - and don't use it for other purposes.
Check the functions for more details.
As it currently stands your code is not safe even with all those efforts - but it's really simple to fix!
try with preg_replace() function and no need of \n\r both you can do with \n or PHP_EOL only
$jawaban = preg_replace('#<br\s*?/?>#i', "\n", $jawaban1);
or
$jawaban = preg_replace('#<br\s*?/?>#i', PHP_EOL, $jawaban1);
you must knowing these before working with strings:
"\n\r" means new line.
'\n\r' doesn't mean new line.
doesn't mean new line. It's just HTML number for HTML Symbols. when you are using it, you mean just show \n\r in your browser. this is answer to your question:
both insert "\r\n" into the text , why is this happening?
so, after knowing that, you understand:
if your $jawaban1 string is
Hello <br> and welcome!
and your code is
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);
It means, $jawaban will be exactly like this:
Hello
and welcome!
without any \n\r and just your browser showing it like this:
Hello \n\r and welcome!
If you want to replace all br by \n\r just use the code in your question:
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
About preg_replace()
When you can use str_ireplace, Don't use preg_replace. str_ireplace is faster.
Don't do it if you don't need it
in your code you did this:
$unsafejawabanfirst = nl2br($jawabannotcut);
and right after that you want to replace br with \n\r. It's like do and undo. I see that you are trying to show it again inside textarea element. so don't replace \n\r with br. the solution? don't change \n\r at all and if you want save it to the db just save it with \r\r. when you need it to show outside of textarea element just use nl2br function.
There is always something that saves my day, it is actually a workaround and your question is a trigger for me to get deeper to this matter - once for all.
For now, here you go - nice & sleek workaround:
There is already nl2br() function that replaces inserts <br> tags before new line characters:
Example (codepad):
<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>
In my database I've
Linetext1 \r\nLinetext2
I then fech data:
while($row = $result->fetch_assoc()) {
$mydata_array = $row['myrow'];
}
then the echo part:
for ($i = 0; $i <5; ++$I){
echo $mydata_array[$i];
}
But it literally output in textarea (and in fpdf) Linetext1 \r\nLinetext2. I did try a string replace as suggested in other questions
echo (str_replace('\r\n', '<br />', $mydata_array[$i]);
but then I literally have
Linetext1 <br />Linetext2
Thanks for your help!
SOLUTION
After Sergey's answer, I used this:
echo (str_replace(array('\r', '\n'), array("", "\n"), $mydata_array[$i]);
PS It's important to use MultiCell and not single Cell
<br /> tags are useless in a textarea, unless it's a rich text editor area (and therefore not exactly a textarea) - it needs \n or \r\n line breaks. FPDF needs \n breaks, too. What you should probably do is to replace the \r and \n literals to actual line breaks:
echo (str_replace(array('\r', '\n'), array("", "\n"), $mydata_array[$i]);
Edit: As per your testing, \r should be wiped out completely, because it only confuses the FPDF without adding any real value.
I have this text in a MySql database:
First paragraph very long.
Second paragraph very long.
Third paragraph.
I add p tags and it works:
$text = preg_replace("/\n/","<p>",$text);
$text = '<p>'.$text;
I try to add line breaks when I echo to a html page. I tried 3 different things. But none of them seem to work:
$text = preg_replace("/<\/p>/","</p>\n\n",$text);
$text = preg_replace("/<\/p>/","</p><br><br>",$text);
$text = nl2br($text);
echo $text;
If I go to the web inspector in the Safari browser, I get this:
<p>First paragraph very long.</p><p>Second paragraph very long.</p><p>Third paragraph.</p>
I would like to have this:
<p>First paragraph very long.</p>\n>\n
<p>Second paragraph very long.</p>\n>\n
<p>Third paragraph.</p>\n>\n
It seems that my regex does not select <\/p> even when I escape it. I do not understand. What is wrong?
Presuming you need newline control chars (and not html line break tags):
$text = "First paragraph very long.\nSecond paragraph very long.\nThird paragraph.";
$text = '<p>' . preg_replace("~\n~", "<p>\n\n</p>", trim($text)) . '</p>;
Note trim is used incase you have leading or trailing newlines, ~ is used as a delimiter, because / is a poor choice when dealing with html, causeing you to escape all over the place.
It is not apparent in the above example, but using some of your reqex as an example:
preg_replace("~</p>~","</p>\n\n",$text);
is much easier to read than:
preg_replace("/<\/p>/","</p>\n\n",$text);
Also, you dont need regex, you could just use str_replace:
$text = '<p>' .str_replace("\n", "<p>\n\n</p>", trim($text)) . '</p>;
Or even explode/implode:
$text = '<p>' . implode("</p>\n\n<p>", explode("\n", trim($text))) . '</p>';
If it was html line breaks you wanted, then you could just edit the replacement argument to:
"</p><br><br><p>"
in any of the above, but it would probably be better to use some css:
p{
margin-bottom:10px;
}
You don't need regex, simple str_replace works (in your example):
$text = str_replace( "</p><p>","</p>\n<p>",$text );
I am trying to do a line break after the message "Original message", I have tried with this but It keeps showing me the
---Original message---<br />
message
<textarea id="txtMessage" rows="10" cols="50"><?php echo nl2br(str_replace('<br/>', " ","---Original message---\n".$array['message']));?></textarea>
I want something likes this:
---Original message---
message
any advise?
This should do what you want it to:
<?php echo str_replace('<br />', " ","---Original message---\n".$array['message']);?>
nl2br — Inserts HTML line breaks before all newlines in a string (from php.net)
Example:
echo "<textarea>HI! \nThis is some String, \nit works fine</textarea>";
Result:
But if you try this:
echo nl2br("<textarea>HI! \nThis is some String, \nit works fine</textarea>");
you will get this:
Therefore you should not use nl2br before saving it to database, otherwise you have to get rid of <br /> every time you try to edit text! Just use it when you print it out as text.
echo nl2br(str_replace('<br/>', " ", ... ));
should be
echo str_replace('<br />', ' ', ... );
The php function "nl2br" takes newlines, and converts them into br tags. If you don't want that, you should probably remove it :).
Heh, beaten by Ryan.
You're trying to replace <br/>, but the original text has <br /> (note the space).
You are removing the HTML breaks, then adding them back! Look at your code:
nl2br(str_replace('<br/>', " ","---Original message---\n".$array['message']))
First, str_replace replaces '<br/>' with a space. Then, nl2br adds a <br> for every newline (\n) it finds.
Remove nl2br call and it's done.
If you want to do nl2br on all of the text except for what's inside the textarea you could do this:
function clean_textarea_of_br($data) {
return str_replace(array("<br>", "<br/>", "<br />"), "", $data[0]);
}
$message = preg_replace_callback('#<textarea[^>]*>(.*?)</textarea>#is',clean_textarea_of_br,$message);