Escaping quote, both " and ' - php

I am trying my best to work this out and it is driving me crazy, I am hoping that I can use either preg_replace or ereg_replace for this.
Basically I am putting out string of text which is taken from a news article, I am taking the first 100 characters rounded to the closest end of word, the problem occurs if a " or ' appears in the 100 characters string and no closing " or ' is present, this then causes my PHP code to fail. So I need to write some kind of replace code so that all " and ' will be replaced with \" and \' so they are escaped and don't affect my PHP.
Update
I cannot correct anything to do with database insertion as I am dealing with a very old archive of data which I cannot process and re-enter into the database so I'm stuck with what I have got there.
This is the code I have:
$text = preg_replace('/\s+?(\S+)?$/', '',substr($text, 0, 100));
echo '<div style="color: #8197cd;" >'.$text.'...</div>';
So that takes my text, shortens it and puts it to the nearest word.
Then I am trying to do something along the lines of:
$text = preg_replace("\"","\"",$text);
$text = preg_replace("\'","\'",$text);
But preg_replace is not a strong point of mine so that is completely wrong!

the problem occurs if a " or ' appears in the 100 characters string and no closing " or ' is present, this then causes my PHP code to fail.
You're trying to fix a problem that shouldn't be there in the first place - most likely unescaped input in a mySQL query. You need to fix that instead (it's also a security problem).
Show the code that breaks, I'm sure someone will be able to point out what needs to be done.

Something seems to be missing from your question. You should consider posting the code that is having a problem.
Having quotes inside a variable you are echoing out is not going to fail. The only thing I could imagine causing an error would be if you were using some sort of template system or code that was taking the string and using it to do an eval() somewhere, but that would be a very poor system.
If you are inserting the string into a database, then you would need to escape those characters, as mentioned by SiteSafeNL.
If an eval is the source of the problem, then htmlentities which he also suggested would fix it.
Added based on latest additions to the question
Please try this:
echo '<div style="color: #8197cd;" >'. htmlentities($text) . '...</div>';
And the preg_replaces are not useful, so simply omit that code.

Don't you need anything like mysql_real_escape_string or htmlentities?

Related

MySQL Column Value Breaking HTML Syntax In OnClick

I am having an issue where a PHP variable's value from a MySQL database is breaking my HTML syntax.
<?php
echo '<a style="cursor: pointer;" onclick="openContentWindow(\''.$row['creativeStrengths'].'\')">Open content</a>';
?>
If the string contains a " or ' it will break my string and give an error.
Is there any way to escape the characters in HTML? Or if there is a way to use javascript/jquery in this situation that's fine too.
The value of $row['creativeStrengths'] is a string by the way hence the single quotes around it.
Thanks!
EDIT: I solved my issue by using addslashes(). Sorry that my question may not have been specific enough. Your answers were most likely right however I may not have clarified enough.
The escape code for " is " and the escape code for ' is '. The entity name for the former is ", but I don't know if there is one for the latter.
Source
Try:
htmlspecialchars($row['creativeStrengths'])
It will escape any HTML character.
I solved my issue by using addslashes().
addslashes($row['creativeStrengths']);

how to replace '\\\' to '\'?

my code is not working ? and i dont want to use str_replace , for there maybe more slashes than 3 to be replaced. how can i do the job using preg_replace?
my code here like this:
<?php
$str='<li>
<span class=\"highlight\">Color</span>
Can\\\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
$str=preg_replace("#\\+#","\\",$str);
echo $str;
There is merit in the other answers, but to me it looks like what you're actually trying to accomplish is something very different. In the php code \\\' is not three slashes followed by an apostrophe, it's one escaped slash followed by an escaped apostrophe, and in the rendered output, that's exactly what you see—a slash followed by an apostrophe (with no need to escape them in the rendered html). It's important to realize that the escape character is not actually part of the string; it's merely a way to help you represent a character that normally has very different meaning in within php—in this case, an apostrophe normally terminates a string literal. What looks like 4 characters in php is actually only 2 characters in the string.
If this is the extent of your code, there's no need for string manipulation or regular expressions. What you actually need is just this:
<?php
$str='<li>
<span class="highlight">Color</span>
Can\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
echo $str;
?>
Only one escape character is needed here for the apostrophe, and in the rendered HTML you will see no slashes at all.
Further Reading:
Escape sequences
The root of this problem is actually in how it was written into your database and likely to be caused by magic_quotes_gpc; this was used in older versions and a really bad idea.
The best fix
This requires a few steps:
Fix the script that puts the HTML inside your database by disabling magic_quotes_gpc.
Write a script that reads all existing database entries, applies stripslashes() and saves the changes.
Fix the presentation part (though, that may need no changes at all.
Alternative patch
Use stripslashes() before you present the HTML.
use this pattern
preg_replace('#\\+#', '\\', $text);
This replaces two or more \ symbols preceding an ' symbol with \'
$theConvertedString = preg_replace("/\\{2,}'/", "\'", $theSourceString);
Ideally, you shouldn't have code causing this issue in the first place so I would have a look at why you have \\' in your code to begin with. If you've manually put it in your variables, take it out. Often, this also happens with multiple calls to addslashes() or mysql_real_escape_string() or a cheap hosting providers' automatic transformation of all POST request variables to escape slashes, combined with your server side PHP code to do the same.

Removing Break Lines

I've asked this question before but I didn't seem to get the right answer. I've got a problem with new lines in text. Javascript and jQuery don't like things like this:
alert('text
text);
When I pull information from a database table that has a break line in it, JS and jQuery can't parse it correctly. I've been told to use n2lbr(), but that doesn't work when someone uses 'shift+enter' or 'enter' when typing text into a message (which is where I get this problem). I still end up with separate lines when using it. It seems to correctly apply the BR tag after the line break, but it still leaves the break there.
Can anyone provide some help here? I get the message data with jQuery and send it off to PHP file to storage, so I'd like to fix the problem there.
This wouldn't be a problem normally, but I want to pull all of a users messages when they first load up their inbox and then display it to them via jQuery when they select a certain message.
You could use a regexp to replace newlines with spaces:
alert('<?php preg_replace("/[\n\r\f]+/m","<br />", $text); ?>');
The m modifier will match across newlines, which in this case I think is important.
edit: sorry, didn't realise you actually wanted <br /> elements, not spaces. updated answer accordingly.
edit2: like #LainIwakura, I made a mistake in my regexp, partly due to the previous edit. my new regexp only replaces CR/NL/LF characters, not any whitespace character (\s). note there are a bunch of unicode linebreak characters that i haven't acknowledged... if you need to deal with these, you might want to read up on the regexp syntax for unicode
Edit: Okay after much tripping over myself I believe you want this:
$str = preg_replace('/\n+/', '<br />', $str);
And with that I'm going to bed...too late to be answering questions.
I usually use json_encode() to format string for use in JavaScript, as it does everything that's necessary for making JS-valid value.

Getting rid of \r\n strings

I have a form into which I entered a newline character which looked correct when I entered it, but when the data is now pulled from the database, instead of the white space, I get the \n\r string showing up.
I try to do this:
$hike_description = nl2br($hike_description);
But it doesn't work. Does anyone know how this can be fixed? I am using PHP.
And here is the page where this is happening. See the description section of the page:
http://www.comehike.com/hikes/scheduled_hike.php?hike_id=130
Thanks,
Alex
Does anyone know how this can be fixed?
Sure.
Your code doing unnecessary escaping, most likely before adding text to the database.
So, instead of replacing it back, you have to find that harmful code and get rid of it.
This means, you have probably plain text '\n\r' strings in the db.
Try to sanitize db output before display:
$sanitized_text = preg_replace('/\\[rn]/','', $text_from_db);
(just a guess).
Addendum:
Of course, as Col. Shrapnel pointed out, there's something fundamentally wrong
with the contents of the database (or, it is used this way by convention and you don't know that).
For now, you have fixed a symptom partially
but it would be much better to look for the reason for these escaped characters
being in the database at all.
Regards
rbo
You can use str_replace to clean up the input.
$hike_description = nl2br(str_replace("\r\n", "\n", $hike_description));
$hike_description = str_replace(array('\n','\r'),'',$hike_description);
You may want to read up on the differences between the single quote and double quote in PHP as well: http://php.net/manual/en/language.types.string.php

PHP Wrap a string in double quotes

I'm attempting to wrap a user-inputted string in double quotes for output but I want to make sure I don't end up with double double quotes on either side of the string. For example, if a user posts
"Hello"
I don't want to turn it into
""Hello""
I can do this fairly easily using the code below, however I'm concerned that this may get slow if I'm looping through lots of strings.
$string = '"'.trim($string,'"').'"';
If anyone has a better way of doing this, that'd be great. Equally, if anybody can confirm that my way is fine, I'll be happy.
Thanks
This is exactly how I would solve this problem. It's only worth worrying about the code being slow if you have a problem with the application being slow, and you can trace it down to the trim statements.
A well known programming quote is "Premature Optimisation is the root of all evil" - see the wikipedia article linked for more on this.
Make a careful consideration of what should happen with all the cases.
(using [] as quotes for readability)
You've said what you do for ["Hello"] but what do you do for [I said "Hello", punk]? Do you still strip the user-input quotes, or do you remove them? Or maybe go one step further and substitute single quotes for double quotes...but then you'd have to consider the cases where the user input contains both single and double quotes! What about when the user puts in "grammatically wrong" text like ["Hello] (no closing quote!).
Best way to ensure you do it right is to make a test case for each edge case you can think of and make sure your proposed solution actually does what is expected.
If the actually reason for this requirement is [I am taking a user's input at some point and then re-displaying it to them at another point, and don't want to show them stupid looking data like [""data""]], you'll probably just want to only remove double quotes from the start or end of the input string, because stripping them from the middle screws with the user's intended data.
If your goal is merely to clearly distinguish between their input and text that they didn't input, consider using other means of highlighting that instead of quotation marks. So instead of [you entered "data"], you could display [you entered data] or [you entered: data] which avoid this problem altogether.
Personally, I'd suggest stripping the quotes on input. As for making it faster, if you allow quotes to be entered or stored, you're always going to be stuck with using an if/else before displaying them.
Obviously, you'd still need to perform a sanity check of the input data regardless of whatever system you end up with.
I did it this way:
function quotize(&$string)
{
if (empty($string) || is_null($string)) {
return;
}
$char = '"';
if ($string[0] != $char) {
$string = $char . $string;
}
if (substr($string, -1) != $char) {
$string .= $char;
}
return;
}
It is common practice to use quotation marks to represent a quote within a quote, if you want to let your users write:
and she said "hey ho"
, which you could turn into:
User: "and she said 'hey ho'"

Categories