Regex Extra Line Error - php

I was having an issue when I input comments into a log table the display would be incorrect.
For example when I input:
1
2
3
It would show up as:
1
2
3
To deal with this problem I commented out some of the code and added this regex line:
//$notes= str_replace("</br>","<br>",$sqlresult['Notes']);
//$notes = str_replace("\r","",$sqlresult['Notes']);
//$notes = str_replace("\n","",$sqlresult['Notes']);
//$notes = str_replace("\\","",$sqlresult['Notes']);
//$notes = str_replace("\r","<P>",$sqlresult['Notes']);
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
However now I am receiving an error when text is pasted from an application that appears as one line is coming up with a lot of extra lines in betweem.
E.g.
Files are.. CDSEYE SUBMIT BY M99-CDSENTD
Display:
Files are...
CDSXEYE
(10 EXTRA BLANK LINES)
SUBMIT BY M99-CDSENTD
Is there anyway I can get the $notes to display input EXACTLY how it is inputted?

The reason you had to use the
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
line in the first place is because there was something wrong with the way you were handling input and storing it in a sql database. We merely plugged that hole by removing that extra newline at the end. If we wanted a true 1 to 1 input to output, we would need to look at the way the data is stored from the input textbox to the sql database. Also how it is being pulled from that database and displayed back to the output. If somebody else wrote this code, then it may take a while to find how that was done.
final answer ended up being:
$notes = trim(preg_replace('/\r\r/', '<br>', $sqlresult['Notes']));

I think the problem lies in the second to last line, where you're replacing \r with <p>, which adds an extra blank line. Try <br> instead.

Your replacing every 2 spaces with a line break (<br>), this would be the reason for your breaks.
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
I suggest remove the above code and then put
echo nl2br($your_text_variable); //in the view

Related

PHP - Insert line break in email post

I've tried many tests to make this work but can't seem to figure this one out!
A PHP code is called before it sends an email, it checks if placeholders have values in them, then adds them in email. Results I get are all on same line with no line breaks.
Can someone please tell me how to insert a line break in the code?
I've tried the linebreak br with single quotes and double in many places in the code, nothing is working. I've tried the echo code, I get errors.
Each placeholder starts with the IF statement and must end with the value}'; for each one. Where and how can I insert the line break between the IF and value}'; for each?
Thanks a million!
Results come out like this scapbooking20dancing35
instead of:
scapbooking
20
dancing
35
if you guys had to put a line break in this code, how does it go? cheers if($_POST['form']['age'] != '') $modAdminEmailText .= '{age:caption}: {age:value}';
/* Retrieve the admin email text */
$modAdminEmailText = $form->AdminEmailText;
/*Checks if the field has a value and if so, add it to the Email Text*/
if($_POST['form']['hobby'] != '')
$modAdminEmailText .= '{hobby:caption}: {hobby:value}';
if($_POST['form']['age'] != '')
$modAdminEmailText .= '{age:caption}: {age:value}';
/*After the field placeholders are added we will need to replace them with the actual submitted values.*/
$adminEmail['text'] = $modAdminEmailText;
$adminEmail['text'] = str_replace($placeholders, $values, $adminEmail['text']);
been there, done that. Here's what I think is going on.
I've tried the linebreak br ... with single quotes and double.. in many many places in the code, nothing is working.. I've tried the echo code, I get errors, 2 days now no sleep :(
using <br> in your code will only work if you write the e-mail as HTML. Check the documentation for the e-mail library you use to see how you do that.
Now in stead of using <br> you may want to use the \n or \r\n symbol. Beware, that if you use that, then you must enclose your string with double quotes: $somevar."\n"
Alternatively try to use PHP_EOL like this: $somevar. PHP_EOL
I'm not sure how these two methods behave when using string interpolation, but it's worth a try.

PHP variables look the same but are not equal (I'm confused)

OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.

Step by step storing textarea mysql php

so i'm getting confused by all the topics about storing and displaying textareas with correct linebreaks and not allowing any HTML markup whatsoever.
Right now i am escaping the input, then storing it as a text and then trying to display it with echo nl2br($text); It still won't work though.
So how is it supposed to be handled so that the input is safe, it won't allow any HTML on display, how to display it correctly and so on?
This is what happens when i run my current code..
Step 1:
Textarea input:
ROW 1
ROW 3
ROW 4
ROW 6
Escaped variable : $text = $mysqli->real_escape_string($_POST['textarea']);
Step 2:
SQL-query to insert into db. Stored in database as:
ROW 1\r\n\r\nROW 3\r\nROW 4\r\n\r\nROW 6
Step 3:
Fetch it with SQL, display with an echo nl2br($text); which results as ROW 1\r\n\r\nROW 3\r\nROW 4\r\n\r\nROW 6
I guess that the way it is stored prohibits the usage of nl2br since there ain't really any newlines stored but only \r etc, i'm kinda lost at this one and it's getting late so...
Any guidance would be appreciated.
In your case - since you want to strip any markup from the input....
$text = strip_tags($_POST['textarea']);
$text = $mysqli->real_escape_string($text);
mysqli->query("INSERT INTO yourtable (content) VALUES ('$text')");
...but when you want to output it again to a browser - you STILL NEED TO escape it appropriately....
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_assoc()) {
print "<div>" . nl2br(htmlentities($row['content'])) . "</div>";
}
}
The only time you apply any sanitization to data within PHP is at the point where it leaves PHP (going to a database, going to a browser, going to a log file....) and the method you use for transforming the data is dependant on where the data is going

New Lines inside DB dont get displayed in textarea

Some strange behaviour with the same script on different Websites here. Here you go:
I have an textarea where users enter text. They also do newlines using enter. That is stored inside the mysql db like this:
Line One\r\nLine Two\r\n\r\nLine Three
The problem occures when displaying that text inside a textarea again.
In most cases everything works fine. The following is displayed inside the textarea:
Line One
Line Two
Line Three
On some websites however only the following is displayed inside the textarea:
Line One
Line Two
Line Three
Inside the db the two newlines (\r\n\r\n) are still there. Only one is displayed however.
This happens like i said only on some websites, in most cases multiple newlines like this \r\n\r\n are displayed fine.
UPDATE:
Seams like JSON has something to do with it. It is an JSON string containing a string like "Line One\r\nLine Two\r\n\r\nLine Three".
{"mystring":"Line One\r\nLine Two\r\n\r\nLine Three"}
$row = $db->load(); // get the json string
var_dump($row); // \r\n\r\n still inside!
$jrow = json_decode($row);
var_dump($jrow->mystring); // on some servers multiple newlines are chopped to one
Try using n2lbr when displaying the DB value in the textarea. Does that help at all? It's worked for me in the past.

PHP to Mysql Line break Question

I am having hard time getting a form submitted textarea where people put in line breaks when they hit enter on their address..For example.
<textarea name="address"></textarea>
I am using this to get the post
$address = mysql_real_escape_string(trim($_POST['address']));
They are entering 123 test <return>city,state.
Then after they submit, in the mysql database the address is showing 123 testnrcity state
So how can I handle this?
Thanks!
Use nl2br?
$address = mysql_real_escape_string(trim(nl2br($_POST['address'])));
HTH :)
Have you checked what's in your database field? Just show the database contents with phpMyAdmin or a similar tool. The line break can either be a line break character or two characters: \n. If it's the latter, then your input probably was escaped twice. Or is it just "n". Then there is probably another escaping somewhere along the way. Do you use a database abstraction layer? Maybe it escapes the values too.
I was not able to resolve this the way I wanted to and just settled with using str_replace() to replace all "\r\n" stuff with a space...

Categories