How to break a text into the next line in php? - php

i have this project which is blog type where I pull posts submitted from the server. The problem is that when the post is echo(ed) the text goes all in one line , how do I make it go to the next line after certain length?
Here is the code where the text is being posted
$postpost = $result["post_user"];
echo " <b>name</b> = " .$result["username"] ."<br>";
echo " <b>post</b> = " .$result["post"] . "<br>";
echo " <b>date</b> = ".$date["date"]. "
<br><br>----------------------<br><br>";
and here is the output problem

Use wordwrap() :
// the 80 is the number of characters after which to break:
echo " <b>post</b> = " . wordwrap($result["post"], 80, '<br>') . '<br>';
You may also be interested in nl2br().

$postpost = $result["post_user"];
echo " <b>name</b> = " .$result["username"] ."<br>";
echo " <b>post</b> = " .chunk_split($result["post"],100,"<br/>") . "<br>";
echo " <b>date</b> = ".$date["date"]. "
<br><br>----------------------<br><br>";
This will break it after 100 characters. You can change the 100 to your needs.
But wordwrap is a better solution :)

You can use wordwrap function in php
<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo $newtext;
?>

echo implode('<br/>',str_split($string,100));

Firstly, if you want the text to have a maximum width, enclose the whole thing in a wrapping <div> element, and use CSS to style it to a maximum width. Any text inside the element with then wrap nicely.
Here's the CSS code you'd need:
#mydiv {width:200px;}
The only text that will still be a problem after that is text without any spaces in it, which would still stretch off the edge of the page.
For these, you can use another CSS property, word-wrap, like so:
#mydiv {word-wrap:break-word;}
The best practice is to keep your CSS code separate from your HTML, but if you're not using stylesheets, you can add the CSS code directly to the <div> element with the style attribute, like so:
<div style='width:200px; word-wrap:break-word;'>
..... (your content goes here) .....
</div>
It is, of course, possible to do word-wrapping in PHP, using it's wordwrap() function (or str_split() for long strings with no spaces), but you'll end up with the lines being varying lengths when displayed on the page, because the font has different widths for different characters. Therefore, I would say that the CSS solution is better because the word wrapping will look better on the page.
Hope that helps.

this should do it :
$newtext = wordwrap($text, 20, "<br />\n");
examples can be found here

Use php's wordwrap() function.
http://php.net/manual/en/function.wordwrap.php

Edit: I initially thought this is a CSS problem. I see that you want to break strings which are very large with php. You can use wordwrap() for that, as artlung recommended.
What I initially thought in CSS: put each blog entry into a div, and assign word-wrap: break-word; for the div and also specify width of the div.
My idea on jsfiddle.com: Link

Related

PHP doesn't show line break in textarea value in echo

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)

str_ireplace or preg_replace replaced break tag into \r\n

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);
?>

text-indent on user formatted text

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

how to combine function and string inside php echo

Can you combine a PHP function and string in the same echo statement? Currently, I have this code that grabs a photo's caption, then shortens it to 25 characters or less, stopping at the nearest blank space so it can fit the whole word.
echo substr($caption,0,strpos($caption,' ',25));
echo " ...";
Example output: changes "This is way too long to fit in this foobar small area preview box" to "This is way too long to..."
I'd like to be able to combine the 'substr' and '...' into the same echo statement. I tried the following, but it didn't work:
echo "{substr($caption,0,strpos($caption,' ',25))} ...";
Any ideas?
The , is great for this, and much faster than the ., which has the overhead of concatenating the string.
echo substr($caption, 0, strpos($caption, ' ', 25)), '...';
EDIT: To clarify, the , just simply sends all the strings, separated by the comma, to echo, and thus is equal to the separate line echo statments. The DOT operator performs concatenation. You can use as many commas as you want, i.e. echo strFunction1(), ' some text ', strFunction2(), '...';
Try:
echo substr($caption,0,strpos($caption,' ',25)) . '...';

Font Size with php and/or CSS

I am trying to produce an effect where I have a title on a page all in Capitals. I would however like to see the first character of each word with a slightly larger font size.
For example:
MY TITLE
The M and T would be in size 16 font and the rest of the word would be in size 12. I am pulling the titles from a database (MySQL) so "MY TITLE" is just an example. It could be any wording.
I realise there is a way to do this using substr (in php) and search for where the spaces are at the end of each word. But this seems to me as though it will get a bit messy with coding.
Does anyone have a better suggestion?
I think something like this is what you are looking for.
PHP
<?php
$text = "My Title";
$newText = preg_replace('/(\w)(\w+\b)/', '<span class="firstLetter">$1</span>$2', $text);
echo $newText; // <span class="firstLetter">M</span>y <span class="firstLetter">T</span>itle
CSS
.firstLetter{font-size: 125%;}
Use the CSS first letter pseudo-element by wrapping each first letter in a <span> tag:
p span:first-letter
{
font-size: 16pt;
}
Pure PHP solution:
<?php
$str = '<h2><big>S</big>ome <big>t</big>ext</h2>';
echo strtoupper($str);
?>
CSS Solution:
<h2><span class="larger">S</span>ome <span class="larger">T</span>ext</h2>
<style type="text/css">
h2{text-transform:uppercase;}
.larger{font-size:larger;}
</style>
ADDITIONAL METHOD: If you want to be able to output a particular format with a variable number of words, you can do something like this:
<?php
$string = 'VariaBle Number oF WORds!';
$words = explode(' ', $string);
$modified = array();
foreach($words as $word)
{
$modified[] = '<big>'.substr($word, 0, 1).'</big>'.substr($word, 1, strlen($word));
}
echo strtoupper(implode(' ', $modified));
?>
Simple CSS property,
font-variant:small-caps;

Categories