How to add new line in php echo - php

The text of story content in my database is:
I want to add\r\nnew line
(no quote)
When I use:
echo nl2br($story->getStoryContent());
to replace the \r\n with br, it doesn't work. The browser still display \r\n. When I view source, the \r\n is still there and br is nowhere to be found also. This is weird because when I test the function nl2br with simple code like:
echo nl2br("Welcome\r\nThis is my HTML document");
it does work. Would you please tell me why it didn't work? Thank you so much.

The following snippet uses a technique that you may like better, as follows:
<?php
$example = "\n\rSome Kind\r of \nText\n\n";
$replace = array("\r\n", "\n\r", "\r", "\n");
$subs = array("","","","");
$text = str_replace($replace, $subs, $example );
var_dump($text); // "Some Kind of Text"
Live demo here
I doubt that you need "\n\r" but I left it in just in case you feel it is really necessary.
This works by having an array of line termination strings to be replaced with an empty string in each case.

I found the answer is pretty simple. I simply use
$text = $this->storyContent;
$text = str_replace("\\r\\n","<br>",$text);
$text = str_replace("\\n\\r","<br>",$text);
$text = str_replace("\\r","<br>",$text);
$text = str_replace("\\n","<br>",$text);

Related

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

Replace " ’ " with " ' " in PHP

I'm grabbing a string from the database that could be something like String’s Title however I need to replace the ’ with a ' so that I can pass the string to an external API. I've used just about every variation of escaped strings in str_replace() that I can think of to no avail.
$stdin = mb_str_replace('’', '\'', $stdin);
Implementation of mb_str_replace() here: http://www.php.net/manual/en/ref.mbstring.php#107631
I mean this:
<?php
function mb_str_replace($needle, $replacement, $haystack) {
return implode($replacement, mb_split($needle, $haystack));
}
echo mb_str_replace('’', "'", "String’s Title");
It may solve encoding problems.
I have just tested this:
echo str_replace('’', "'", $cardnametitle);
//Outputs: String's Title
Edit: I believe that entries in your database have been htmlentitiesed.
Note: I'm pretty sure this is not a good solution, even though it did solve your problem I think there should be a better way to do it.
Try this
$s = "String’s Title";
$h = str_replace("’","'",$s);
echo $h;
Also can Try with preg_replace
echo preg_replace('/\’/',"'","String’s Title");
I don't know why str_replace() is not working for you.
I feel you haven't tried it in correct way.
Refer LIVE DEMO
<?php
$str = "String’s Title";
echo str_replace('’', '\'', $str) . "\n";
echo str_replace("’", "'", $str);
?>
OUTPUT:
String's Title
String's Title
UPDATE 1:
You may need to try setting the header as
header('Content-Type: text/html; charset=utf-8');
I came across a similar issue trying to replace apostrophes with underscores... I ended up having to write this (and this was for a WordPress site):
$replace = array(",","'","’"," ","’","–");
$downloadTitle = str_replace( $replace,"_",get_the_title($gallery_id));
I'm new to PHP myself, and realize this is pretty hideous code, but it worked for me. I realized it was the "’" that REALLY needed to be factored in for some reason.

preg_replace question

I'm trying to use preg_replace to strip out a section of code but I am having problems getting it to work right.
Code Example:
$str = '<p class="code">some string here</p>';
PHP I'm using:
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
preg_replace($pattern,"", $str);
This strips out the code just as I want with the exception of the space between the p and class.
Returns:
some string here //notice the single space at the beginning.
I'm trying to get:
some string here //no space at the beginning.
I have been beating my head against the wall trying to find a solution. The reason I'm trying to strip it out in a chunk instead of breaking the preg_replace into pieces is because I don't want to change anything that may be in the string between the tags. Any ideas?
That does not happen for me (and it shouldn't).
It may be a space output somewhere else (use var_dump() to view the string).
You might want to look into this thread to see if you want to switch to using DOMDocument. It'll save you a great deal of headaches trying to parse through HTML.
Robust and Mature HTML Parser for PHP
test:
<?php
$str = '<p class="code">some string here</p>';
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
$result = preg_replace($pattern,"", $str);
var_dump($result);
result:
php pregrep.php
string(16) "some string here"
seems to work just fine.
Alex I figured out where I was picking up the extra space.
I was putting that code into a text area like this:
$str = '<p class="code">some string here</p>';
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
$strip_str = preg_replace($pattern,"", $str);
<textarea id="code_area" class="syntaxhl" name="code" cols="66" rows="5">
<?php echo $strip_str; ?>
</textarea>
This gave me my extra space but when I changed the code to:
<textarea id="code_area" class="syntaxhl" name="code" cols="66" rows="5"><?php echo $strip_str; ?></textarea>
No line spaces or breaks the extra space went away.
Why not use trim()?
$text = trim($text);
This removes white spaces around strings.

Formatting text received via api

I get text via api and sometimes the text can be like so:
hello
world!
How are you?
But I do need the text to be like this:
hello world! How are you?
How to do that?
you can replace the newlines in the text by doing:
$newmsg = str_replace("\n",' ',$yourmsg);
Here is the link to the php function documentation:
http://php.net/manual/en/function.str-replace.php
EDIT: I added a space in the code so it does "hello world..." instead of "helloworld"
Use
$str=" test
hello
world" ;
str_replace ( "\n"," " , $str
) ;
If you want number of replaced count pass the fourth argument
str_replace ( "\n"," " , $str , $count ) ;
$str=<<<EOF
hello
world!
How are you?
EOF;
$s = explode("\n",$str);
print_r(implode(" ",$s));
Here is a really ridiculous solution that I would probably use (bear in mind, ocdcoder's answer works just fine), to make sure I accounted for all possible line endings:
$line_ends = array("\r\n", "\r", "\n"); //notice the order is important.
$new_msg = str_replace($line_ends, " ", $orig_msg);
This way, if there are double line ends, it gets rid of them, but if not, it goes back and checks for single line endings.
But if you want to get more complicated, you could replace your possible carriage-returns with line-ends:
$msg_newline_fix = str_replace("\r", "\n", $orig_message);
$msg_double_newline_fix = str_replace("\n\n", "\n", $msg_newline_fix);
$newmsg = str_replace("\n", " ", $msg_double_newline_fix);
But again, I'm a bit wacky like that. Another crazy solution might be:
$msg_newline_fix = str_replace("\r", "\n", $orig_message);
$msg_array_lines = explode("\n", $msg_newline_fix);
foreach($msg_array_lines as $msg_line){
$clean_line = rtrim($msg_line);
if($clean_line !== '') {
$msg_clean_array[] = $clean_line;
}
}
$new_msg = implode(" ", $msg_clean_array);
But if you know your line endings will be new lines (\n) and not carriage returns (\r) then you are probably safe with a simple one line str_replace.
Finally, you might actually want to preserve line endings when it indicates a new paragraph, something like:
Hello
World!
This is a
new paragraph.
In which case, I would suggest normalizing the line-endings first (making it consistently the same thing so we aren't guessing) and then replacing those empty lines with some kind of safe token you can go back and replace with your new line. Something like:
$msg_carriage_fix = str_replace("\r", "\n\n", $orig_message);
$msg_double_carriage_fix = str_replace("\n\n\n", "\n\n", $msg_newline_fix);
Now we are at the point where we know each line, including empty lines, have only one \n at the end. By replacing the potential \r with two \n, and then replacing only three \n in a row with two \n we avoid the risk of removing any line endings if there were no carriage-return \rs in the first place. Then we can finally do:
$msg_hold_true_linebreaks = str_replace("\n\n", "%line-break%", $msg_double_carriage_fix);
$msg_strip_new_lines = str_replace("\n"," ",$msg_hold_true_linebreaks);
and last but not least:
$new_msg = str_replace("%line-break%","\n",$msg_strip_new_lines);
But,that is only if you really want to keep those true line-breaks and if you want to be extra sure you are ready for carriage-returns, line-ends, and the dreaded \r\n.
I would show yet another version that may shorter and involves using implode and explode, but I'm sure that's enough for now.
edit
Here is a slightly simpler version of that last suggestion, which tries to account for both line endings and intentional line breaks:
$msg_rn_fix = str_replace("\r\n", "\n", $orig_msg);
$msg_r_fix = str_replace("\r", "\n", $msg_rn_fix);
We now know each line ends with a single \n, including empty lines...
$msg_array = explode("\n", $msg_r_fix);
Normal lines each get an array value, but we also know that if the array value is nothing, that it was an intentional hard return...
foreach($msg_array as $msg_line) {
$clean_msg_lines[] = ($msg_line == '') ? "\n" : $msg_line;
}
then we put it all back together:
$new_msg = implode(" ", $clean_msg_lines);
The only flaw is that there will be an extra space before and after each line end. This is easily fixed:
$new_msg = str_replace(" \n ", "\n", $new_msg);
I like this last solution so much, I'm going to copy it below without commentary.
My favorite version
$msg_rn_fix = str_replace("\r\n", "\n", $orig_msg);
$msg_r_fix = str_replace("\r", "\n", $msg_rn_fix);
$msg_array = explode("\n", $msg_r_fix);
foreach($msg_array as $msg_line) {
$clean_msg_lines[] = ($msg_line == '') ? "\n" : $msg_line;
}
$new_msg = implode(" ", $clean_msg_lines);
$new_msg = str_replace(" \n ", "\n", $new_msg);

What is the best way to strip out all html tags from a string?

Using PHP, given a string such as: this is a <strong>string</strong>; I need a function to strip out ALL html tags so that the output is: this is a string. Any ideas? Thanks in advance.
PHP has a built-in function that does exactly what you want: strip_tags
$text = '<b>Hello</b> World';
print strip_tags($text); // outputs Hello World
If you expect broken HTML, you are going to need to load it into a DOM parser and then extract the text.
What about using strip_tags, which should do just the job ?
For instance (quoting the doc) :
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> Other text';
echo strip_tags($text);
echo "\n";
will give you :
Test paragraph. Other text
Edit : but note that strip_tags doesn't validate what you give it. Which means that this code :
$text = "this is <10 a test";
var_dump(strip_tags($text));
Will get you :
string 'this is ' (length=8)
(Everything after the thing that looks like a starting tag gets removed).
strip_tags is the function you're after. You'd use it something like this
$text = '<strong>Strong</strong>';
$text = strip_tags($text);
// Now $text = 'Strong'
I find this to be a little more effective than strip_tags() alone, since strip_tags() will not zap javascript or css:
$search = array(
"'<head[^>]*?>.*?</head>'si",
"'<script[^>]*?>.*?</script>'si",
"'<style[^>]*?>.*?</style>'si",
);
$replace = array("","","");
$text = strip_tags(preg_replace($search, $replace, $html));

Categories