imagettftext \\n line break puzzle - php

in PHP imagettftext, should I be able to make line breaks with "\n" in a string like this?
// The text to draw
$text = 'Something\nElse';
When I try this, the text outputted reads "Something\\nElse" with 2 back slashes before the n.
This does not result in a line-break.
Firstly, SHOULD a single slash n make a line break (\n)?
Secondly, How do i get it to work?
Thanks

\n is a line break only when the string is delimited with double quotes.
echo 'Something\nElse'; // outputs Something\nElse
echo "Something\nElse"; // outputs Something
// Else

Related

Converting \r\n to line breaks in a textarea (not using a <br> tag) in PHP

I have searched throughout this site and google, and could not find a viable solution. There are solutions, but none seem to work for me.
I have a text area that serves as the input for a form, as well as the output (editable) when displaying the form to edit. So, I have a textarea like so:
echo '<textarea>'.$resolution.'</textarea>';
If I enter something with line breaks, it is interpreted as \r\n wherever there is a carriage return. Example:
Input:
This is a
test.
Output:
This is a\\r\\n\\r\\ntest.
Now, I found it simple to remove the extra slash by using stripslashes as follows:
$resolution = stripslashes($resolution);
...but, now the output is:
This is a\r\n\r\ntest.
I cannot figure out how to convert \r\n to a line break (that is, without using a tag, since that would only output <br> within the textarea, where html would not be supported. I've tried all of the following, but none of them worked:
//Effort 1
$resolution = trim($resolution);
//Effort 2
$resolution = nl2br($resolution);
//Effort 3
$resolution = htmlentities($resolution);
//Effort 4
$resolution = preg_replace("\\r\\n","<br>",$resolution);
I'm now at a complete loss. Can anyone shed some light on this?
PHP has two different string building modes. The first uses single quotes, and will do absolutely no variable or special character substitutions. That's what you're using.
The second is variable-embedding in double quoted strings, which should work:
$text = str_replace("\\", "\", $text);
echo "<textarea>$text</textarea>";
The \r and \n should now be active carriage return and newline characters in your output, not the character "slash" and then an 'r' or 'n'
Just use double quotes on str_replace
str_replace('\r',"\r",str_replace('\n',"\n",$resolution));
http://php.net/manual/en/language.types.string.php
or if you're really dealing with double backslashes:
str_replace('\\\\r',"\r",str_replace('\\\\n',"\n",$resolution));

Newline inside variable string

What if I have a long input of string? maybe 50-250 characters.
and I echoed the variable it would echo a very long line of letters and words.
So, how will I let the variable auto Newline itself? maybe after 50 characters it would new line when echoed.
I have thought of counting the length of the string and looping it and after counting 50 characters it would Newline but if i do that it would slow down the Site.
is there any function to Newline a VARIABLE STRING? or i should use Looping instead?
You can use a built-in PHP function: wordwrap.
If you want to cut at 50 characters and insert a HTML line-break:
wordrap($str, 50, "<br />");
You can also use the last parameter to force return, even if the string does not contain spaces.
You can insert escape characters into a string, such as \n which will be translated to a new line break.
You can use PHP_EOL in conjunction with strlen() to acheive what you want.
Just adding more info about \n:
// PHP 5.5.12
// This works for outputing to browser:
$XmlHeader = '<?mso-application progid="Excel.Sheet"?>' . "\n";
// These do NOT work:
$XmlHeader = '<?mso-application progid="Excel.Sheet"?>' . '\n';
$XmlHeader = '<?mso-application progid="Excel.Sheet"?>\n';
If you can manage the string in php i think the definitive solution is using function wordwrap: http://www.php.net/manual/en/function.wordwrap.php
You can set the max lenght of a row, the braek parameter (in your case /n).
The function returns a string with the /n breaks and you can print it.

Remove line from end of file with PHP

How would I remove a line from the end of a string with PHP? Thanks.
You want to remove whitespace? Try trim(). It's close cousins ltrim and rtrim may be closer to what you want.
If you are looking to remove the last line is a string containing new line character (\n), then you'd do something like this ...
$someString = "This is a test\nAnd Another Test\nAnd another test.";
echo "SomeString BEFORE=".$someString."\n";
// find the position of the last occurrence of a \n
$firstN = strlen($someString) - strpos(strrev($someString), "\n");
// get rid of the last line
$someString = substr($someString, 0, $firstN);
echo "SomeString AFTER=".$someString;
if you're trying to remove a line from an end of a file, you could try using PHP's file() function to read the file (which places it into an array) and then pop the last element. This is assuming that php is recognizing the line endings in your file.
$subject = 'Text
written
with
lines';
echo preg_replace('/\\n[^\\n]*\\n?$/', '', $subject);
With feature, that there can be one special newline at the end which is ignored, 'cause it is often a good convention to let one at the end of a file (assuming you are reading string from a file).

file_put_contents, file_append and line breaks

I'm writing a PHP script that adds numbers into a text file. I want to have one number on every line, like this:
1
5
8
12
If I use file_put_contents($filename, $commentnumber, FILE_APPEND), the result looks like:
15812
If I add a line break like file_put_contents($filename, $commentnumber . "\n", FILE_APPEND), spaces are added after each number and one empty line at the end (underscore represents spaces):
1_
5_
8_
12_
_
_
How do I get that function to add the numbers the way I want, without spaces?
Did you tried with PHP EOL constant?
file_put_contents($filename, $commentnumber . PHP_EOL, FILE_APPEND)
--- Added ---
I just realize that my file editor does the same, but don't worrie, is just a ghost character that the editor places there to signal that there is a newline
You could try this
A file with EOL after the last number looks like:
1_
2_
3_
EOF
but a file without that last character looks like
1_
2_
3
EOF
where _ means a space character
You could try to parse the file contents using php to see what's inside
$lines = explode( PHP_EOL, file_get_contents($file));
foreach($lines as $line ) {
var_dump($line);
}
...tricky
pauls answer has the correct approach but he has a mistake.
what you need ist the following:
file_put_contents($filename, trim($commentnumber).PHP_EOL, FILE_APPEND);
the PHP_EOL constant makes sure to use the right line ending on mac, windows and unix systems
the trim function removes any newline or whitespace on both sides of the string.
converting to integer would be a huge mistake because
1. you might end up having zero, expecially because of white space or special characters (wherever they come from...)
2. ids dont necessarily need to be integers
Ohh Guys! Just Use
\r\n
insted of \n
There is nothing in the code you provided that would generate those spaces, unless $commentnumber already contains the space to begin with. If that is the case, simply use trim($commentnumber) instead.
There is also nothing in your code that would explain empty lines at the bottom of the file, unless $commentnumber can be an empty string. If that is the case, and you want it to output the number 0 instead, use intval($commentnumber).
Of course, you need only one of those two. If you want to preserve string-like content, use trim(); if you always want integers, use intval(), which already trims it automatically.
It is also possible that you accidentally wrote " \n" instead of "\n" in your actual code, but in the code you posted here it is correct.
annoyingregistration, what you have there is absolutely fine.
PHP_EOL and "\n" are exactly the same.
The code you provided theres nothing wrong with it so it must be the value of $commentnumber that has a space at the end of it. as stated, run your $commentnumber through the trim() function.
file_put_contents($filename, trim($commentnumber . "\n"), FILE_APPEND);
Good luck.
After reading your code and responses, I have come up with a theory...
Since I can't see that there's anything wrong with your code, how did you open and read the file? Did you actually open it in a text editor? Did you use a PHP script to do it? If so, open the file with a text editor and check that there are actually spaces at the end of each line. If there is actually is...well, ignore the rest of this answer, then. If not, just read on.
For instance, if you use something like this:
<?php
$lines = file($filename);
if($lines) // Error reading
die();
foreach($lines as $line)
echo $line."<br />";
Then you would always a whitespace at the end of the line because of the way file() work. Make sure each $line does not have a whitespace - such as a newline character - at the end.
Since HTML handles all whitespaces - spaces, tabs, newlines etc. - as spaces, if there is a whitespace at the end of $line, then those would appear as spaces in the HTML output.
Solution: use rtrim($line) to remove whitespaces at the end of the lines. Using the following code:
<?php
$lines = file($filename);
if($lines) // Error reading
die();
foreach($lines as $line)
echo rtrim($line)."<br />";
wouldn't have the same problems as the first example, and all spaces at the end of the lines would be gone.
its because each time you write to the file, the file is being finished, file_put_contents inserts an extra line break at the end

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