How to replace tab with in PHP? - php

In my database I have the following text:
for x in values:
print x
I want to print this code on my HTML page. It is printed by PHP to the HTML file as it is. But when HTML is displayed by a browser I, of course, do not see text in this form. I see the following:
for x in values: print x
I partially solved the problem by nl2br, I also use str_replace(' ','&nbsp',$str). As a result I got:
for x in values:
print x
But I still need to shift print x to the right. I thought that I can solve the problem by str_replace('\t',' ',$str). But I found out that str_replace does not recognize the space before the print as '\t'. This space is also not recognized as just a space. In other words, I do not get any before the print.
Why? And how can the problem be solved?

Quote the text in double quotes, like this
str_replace("\t", ' ', $str);
PHP will interpret special characters in double quoted strings, while in single quoted strings, it will just leave the string, with the only exception of \'.
Old and deprecated answer:
Copy the tab character (" ") from notepad, your databasestring or this post, and add this code:
str_replace(' ',' ',$str);
(this is not four spaces, it is the tab character you copied from notepad)

You need to place \t in double quotes for it to be interpreted as a tab character. Single quoted strings aren't interpreted.

always use double quotes when using \t \n etc

It can be tricky because tabs don't actually have a fixed size and you'd have to calculate tab stops. It can be simpler if you print blank space as-is and instruct the browser to display it. You can use <pre> tags:
<pre>for x in values:
print x</pre>
... or set the white-space CSS property:
div.code{
white-space: pre-wrap
}
(As noted by others, '\t' is different from "\t" in PHP.)

Related

why remove "\n","\r","\t" in phalcon?

I found that in the muilti-module which is created by phalcon-tool has these code:
$application = new Application($di);
echo str_replace(["\n","\r","\t"], '', $application->handle()->getContent());
Why remove "\n","\r","\t"?
As Spangen pointed out, these are the escape sequences for some special 'whitespace' characters.
This link here has more information on them: http://us3.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
Now, an important note: for them to work as intended in PHP, you need to enclose them in double quotes, like: "\t", "\n". Single quotes won't produce the intended effects of these escape sequences: '\t', '\n'.
To illustrate this more, you can run this code and see the results. Running it from console like php myfile.php might cause some visual glitches, and running it in the browser will need that you view the 'source code'.
echo "Let's test... ";
echo "Because no new line characters were added, this sentence will be printed in the same line as the previous phrase.";
echo "\n";
echo "But now a new line was added, by typing \\n enclosed in double quotes.";
echo "\n";
echo "Now, let's add a tab, between the next two words: hello \t there.";
echo "\n";
echo "Now, let's add a carriage return, which will 'force' the 'cursor' in this string to move to the beginning, thus 'splitting' this string into two. Adding it now: \r There, I just added it before this last sentence.";
echo "\n";
echo 'Finally, these special characters will not work as intended if we just enclose the string with single quotes, as done in this string: \n \t \r';
This link here has more information on the difference between new lines and carriage returns: https://stackoverflow.com/a/12747850/466395
So yeah, in the original code that you posted, the person removed those special characters using str_replace(), because they tend to produce 'visual glitches' (unintented malformed output) in console.
This is to replace newlines, line feeds and tabs with a single space so that the application's details can be written to STD_OUT as a single line with no wrapping.

escape sequences are not working in 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

PHP trimming spaces unnecessarily?

Let's say I have a variable $foo:
$foo = " a a blablabla a a";
But when I do var_dump($foo) the following gets outputted:
string(57) " a a blablabla a a"
It's like the length (57 in this case) it's correct and it counts the spaces, but it doesn't display them.
How can I display the full string, including the multiple spaces in between the other characters?
If you use <pre> tag the text appears in the brower as you typed it. Couple of links:
http://www.tizag.com/htmlT/htmlpre.php
http://www.htmlcodetutorial.com/linepar/_PRE.html
You could also replace spaces with non breaking space .
Web browsers ignore a lot white space in the code which is nice. Otherwise we wouldn't be able to intend our source code or use newlines much...
Are you by any chance doing this in a browser. If so you need to do this.
<pre>
<?php echo var_dump($foo); ?>
</pre>
Because I just tried in command line and I get the output with spaces. Browsers don't handle multiple spaces and they trim them down. If you want a browser to handle multiple spaces you have to use the output inside a <pre> tag or use instead of spaces.
something like echo str_replace(' ', ' ',$test);

Can't see new lines on textarea - what could the problem be?

I have a php string with a lot of information to be displayed inside a textarea html element.
I don't have access to that textarea nor to the script (if any) that generates it.
$somestring = 'first line \nSecond line \nThird line.';
$somestring as NOT been "worked" with trim or filter_var. Nothing.
On the textfield, I get the \n printed on the textarea hence, not interpreted.
What can I try in order to have those new lines applied?
Thanks in advance.
Try wrapping $somestring with " (double quotes) instead of ' (single quotes)
\n, \r and other backslash escape characters only works in double quotes and heredoc. In single quotes and nowdoc (the single quote version of heredoc), they are read as literal \n and \r.
Example:
<?php
echo "Hello\nWorld"; // Two lines: 'Hello' and 'World'
echo 'Hello\nWorld'; // One line: literally 'Hello\nWorld'
echo <<<HEREDOC
Hello\nWorld
HEREDOC; // Same as "Hello\nWorld"
echo <<<'NOWDOC'
Hello\nWorld
NOWDOC; // Same as 'Hello\nWorld' - only works in PHP 5.3.0+
Read more about this behaviour in the PHP manual
EDIT:
The reason single and double quotes behave differently is because they are both needed in different situations.
For instance, if you would have a string with a lot of new lines, you would use double quotes:
echo "This\nstring\nhas\na\nlot\nof\nlines\n";
But if you would use a string with a lot of backslashes, such as a file name (on Windows) or a regular expression, you would use single quotes to simplify it and avoid having unexpected problems by forgetting to escape a backslash:
echo "C:\this\will\not\work"; // Prints a tab instead of \t and a newline instead of \n
echo 'C:\this\would\work'; // Prints the expected string
echo '/regular expression/'; // Best way to write a regular expression
$somestring = "first line \nSecond line \nThird line.";
http://php.net/types.string <-- extremely useful reading
this article is a cornerstone of PHP knowledge and it's just impossible to use PHP without it.
unlike most of manual pages which are are just for quick reference, this very page is one which every developer should learn by heart.

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.

Categories