escape sequences are not working in php - php

if im not wrong \n representation means that a newline as <br> .But when i use <br> or another tags they work properly but escape sequences.
example
echo "write somethings<br>";
echo "about coding";
above example works fine but when i try to use escape sequences none of them are not working
echo "write something\n";
echo "about coding";
it's just an example for newline character and the other escaping characters dont work as \n.What is the real logic on this case?

\n and other similar escape sequences are not part of HTML. You should use HTML escape sequences. These can be found here: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
So only your <br> tag works but \n is not

No, this is an example of HTML rules.
Putting \n in a PHP string and then outputting it as HTML will put a new line character in the HTML source code. It's just line pressing return when writing raw HTML.
HTML puts no special meaning on the new line character (at least outside of script elements and elements with various non-default values of the CSS white-space property) and treats it like any other white space character.
<br>, on the other hand, is a line break element (but usually an indication that you should be using a block level element around the content instead).

HTML ignores carriage return and linefeed characters, treating them as whitespace. If you want to use display a string formatted with "\n" you can use nl2br to convert it, e.g.
echo nl2br("this is on\ntwo lines");

If you look at this in the browser it wont work : browser knows only HTML for display (<br>) but not escape like \n or \r

Related

Convert \u emoji string to utf-8 for email body

I am having the following emoji in a PHP string variable
$emoji = "\u{1F9D1}\u{1F4AC}";
echo $emoji;
This code above will print the following emoji.
🧑💬
I wanted to embed these emojis inside an Email body. For this, I want to convert them to &#x1F9D1&#x1F4AC so that I can place them in the Email body and they will show up correctly.
How do I do this in PHP?
$foo = preg_replace('#\\\u\{(.*?)\}#', '&#x$1;', $emoji);
\u needs to be escaped because it has special meaning in a regular expression, and since the backslash also has special meaning in PHP text literals, we need three of them here.
{ and } also have special meaning, so they need to get escaped with a single backslash.
(.*?) matches everything (expect newlines), ? makes it ungreedy.
I added an ; at the end in the replacement - browsers are fault tolerant when it’s missing, but it is technically required by HTML syntax.
And the “other direction”, as requested:
$emojihtml = '🧑💬';
$bar = preg_replace('~&#x(.*?);~', '\u{$1}', $emojihtml);
(I used ~ for the regex delimiters here, because # is part of what we want to match, saves on escaping.)

%0D%0A not creating a newline when echo is called

Every time I try to echo a string there is no new line. I how can I make a newline when calling echo in php using the $_GET?
here is my code:
<?php
$text = "Hello world";
$text2 = $_GET['msg'];
echo $text2
?>
and this is what I enter in the url:
http://localhost/hello.php?msg=hello%0Dworld
or this one:
http://localhost/hello.php?msg=hello%0Aworld
and even this one:
http://localhost/hello.php?msg=hello%0D%0Aworld
The echo has to be a newline please don't say I should use a different method than $_GET. It has to be $_GET
While performing your exercises you are creating an HTML page.
HTML is a special markup language, which renders according to set of rules, some of them are:
<> characters has a special meaning of control structures named tags
all newline characters are ignored
to make a newline on the page, one have to use suitable tag - such as <br>, <p> or whatever.
So, to make a newline appear on your page, you have to convert newline characters to tags. Either use nl2br() function to get a <br /> tag or str_replace() if you want any other one
Be aware that echoing any request variables without validating them is a considerable security risk! If you want to publish any application with this code it needs to be redesigned.
As common sense states, the conversion from urlencoded to the corresponding character is automatically done by php, but HTML does not render such characters, so you either need to convert them into linebreaks or enclose the message in <pre> tags.

Saving source code from HTML textarea to file

I am saving C++ code from a textarea of an HTML form using PHP.
The problem is if my code is like below,
printf("%d\n");
printf("%d\n");
the code that is saved to the file is like this:
printf(\"%d\\n\");\nprintf(\"%d\\n\");
I want the original code to be saved in the file. If I use,
$sourceCode = str_replace('\n',"\n", $sourceCode);
$sourceCode = str_replace('\"',"\"", $sourceCode);
the result is like below (saved in the file):
printf("%d\
");printf("%d\
");
It is clear that replacing \n in the source code replaces all the HTML created \n along with the \n that user gave as input (the original text). The only difference is user's input has an additional \ before the \n, that is \\n.
How can I resolve the problem such that only the implicit escape characters will be replaced, but the explicit escape characters, that the user wrote himself, will not be changed?
As mentioned by KenB, we need to see the PHP code that you are using to process the form input.
Processing Form Input
It looks to me like addslashes has been used on the form input.
If you are doing that in your code, don't. This is not the proper way to process form input. Instead, you should use the correct function (such as htmlspecialchars or mysqli_real_escape_string) to escape the input before you use it. Read about addslashes.
If you are using an older version of PHP where magic_quotes_gpc is on by default, then you should fix that. Read about 'Disabling Magic Quotes'.
Stripping Out the Slashes
If you have no control over the code that is adding the slashes, then you can remove them with a simple PHP function called stripslashes.
$sourceCode = stripslashes($sourceCode);
Read about stripslashes.
Understanding Escape Sequences
Your str_replace code shows a lack of understanding about escape sequences and/or a lack of understanding about single vs double quotes.
In the following code, a literal \n is replaced with a line break. With the double quotes, PHP interprets the \n as an escape sequence rather than a literal string.
$sourceCode = str_replace('\n',"\n", $sourceCode);
What you want is to replace a literal \\n with a literal \n. Note that to specify a literal backslash it must be doubled; hence the triple backslash you see below.
$sourceCode = str_replace('\\\n', '\n', $sourceCode);
And although this next line accomplishes what you wanted...
$sourceCode = str_replace('\"',"\"", $sourceCode);
...it could have been written differently. The following code is easier to read, saves you having to escape the literal ", and doesn't require PHP to interpret the string.
$sourceCode = str_replace('\"', '"', $sourceCode);
I've given the above code as examples to explain how PHP interprets escapes sequences, but don't use them. Either avoid adding the slashes in the first place or strip them using the proper function, as explained in the first part of this answer.
Read more about escape sequences and quoting strings.
The Literal \n Between Lines
I'm not sure what you are doing to add the literal \n between the lines. We'd need to see your code. But to remove it after the fact, you could try the following
$sourceCode = str_replace(';\n', ";\n", $sourceCode);
Of course, then you'd likely need to correct other C++ end-of-line sequences. So it is better to not add it in the first place.

PHP Linefeeds (\n) Not Working

For some reason I can't use \n to create a linefeed when outputting to a file with PHP. It just writes "\n" to the file. I've tried using "\\n" as well, where it just writes "\n" (as expected). But I can't for the life of me figure out why adding \n to my strings isn't creating new lines. I've also tried \r\n but it just appends "\r\n" to the line in the file.
Example:
error_log('test\n', 3, 'error.log');
error_log('test2\n', 3, 'error.log');
Outputs:
test\ntest2\n
Using MAMP on OSX in case that matters (some sort of PHP config thing maybe?).
Any suggestions?
Use double quotes. "test\n" will work just fine (Or, use 'test' . PHP_EOL).
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
http://php.net/manual/en/language.types.string.php
\n is not meant to be seen as a new line by the end user, you must use the html <br/> element for that.
/n only affects how the html that is generated by php appears in the source code of the web page. if you go to your web page and click on 'view source' you will see php-generated html as one long line. Not pretty. That's what \n is for ; to break that php-generated html into shorter lines. The purpose of \n is to make a prettier 'view source' page.
When you run a PHP script in a browser, it will be rendered as HTML by default. If the books you’re using show otherwise, then either the code or the illustration is inaccurate. You can use “view source” to view what was sent to the browser and you’ll see that your line feeds are present.
<?php
echo "Line 1\nLine 2";
?>
This will render in your browser as:
Line 1 Line 2
If you need to send plain text to your browser, you can use something like:
<?php
header('Content-type: text/plain');
echo "Line 1\nLine 2";
?>
This will output:
Line 1
Line 2
nl2br() function use for create new line
echo nl2br("Welcome\r\n This is my HTML document", false);
The above example will output:
Welcome
This is my HTML document
I'm pretty sure you are outputting to a html file.
The problem is html ignores newlines in source which means you have to replace the newlines with <br/> if you want a newline in the resulting page display.
You need to use double quotes. Double quotes have more escape chars.
error_log("test\n", 3, 'error.log');
error_log("test2\n", 3, 'error.log');
to place the \n in double quotes try
$LOG = str_replace('\n', "\n", $LOG);
It's because you use apostrophes ('). Use quotationmarks (") instead. ' prompts PHP to use whatever is in between the apostrophes literally.
Double quotes are what you want. Single quotes ignore the \ escape. Double quotes will also evaluate variable expressions for you.
Check this page in the php manual for more.
The “\n” or “\r” or similar tags are treated as white-space in HTML and browsers. You can use the "pre" tag to solve that issue
<?php
echo "<pre>";
echo "line1 \n some text \t a tab \r some other content";
echo "</pre>";
?>
If you want to print something like this with a newline (\n) after it:
<p id = "theyateme">Did it get eaten?</p>
To print the above, you should do this:
<?php
print('<p id = "theyateme">Did it get eaten?</p>' . "\n");
?>
The client code from above would be:
<p id = "theyateme">Did it get eaten?</p>
The output from above would be:
Did it get eaten?
I know it's hard, but I always do it that way, and you almost always have to do it that way.
Sometimes you want PHP to print \n to the page instead of giving a newline, like in JavaScript code (generated by PHP).
NOTE about answer: You might be like: Why did you use print instead of echo (I like my echo). That is because I prefer print over echo and printf, because it works better in some cases (my cases usually), but it can be done fine with echo in this case.

Preserving enters in user's input by PHP

How can you preserve "enters" given by the user in the database and show them then to other users?
I store the question of the user and use the following functions to sanitize the user data, prepare it, and execute the SQL command, respectively.
pg_escape_string
pg_prepare
pg_execute
I use htmlentities with ENT_QUOTES to convert the data HTML.
This procedure removes all enters, apparently in the form \n, in the question.
I would like to have a similar question-system as in SO: to show only double enters to users as line breaks.
After you call htmlentities(), call nl2br(). The web browser ignores plain newline characters so you need to convert them to <br /> elements to make them show up.
nl2br — Inserts HTML line breaks before all newlines in a string
Description
string nl2br ( string $string [, bool $is_xhtml= true ] )
Returns string with <br /> or <br> inserted before all newlines.
For example:
echo nl2br(htmlentities($input));
To only show double newlines and ignore single ones, you could instead use a more sophisticated string replacement function, preg_replace:
echo preg_replace('/\n\s*\n/', "<br />\n<br />\n", htmlentities($input));
Here '/\n\s*\n/' matches a newline, followed by any amount of whitespace, followed by another newline. It replaces any such substring with two <br /> elements. Single newlines are ignored. It's also nice because it'll ignore extraneous spaces and tabs that are invisible, such as if a user typed this:
This is a paragraph.\n
It is pretty short.\n
<space><tab>\n
Here's another paragraph.\n
It too is short.
PHP's nl2br() function should do the trick and allow you to convert \n characters to <br> html tags.
To enable the "two enters for a newline" behavior, you should run a regex to turn every pair of consecutive <br> tags into a single <br> tag (you could also do this with \n characters before running nl2br() on the text).

Categories