My PHP application adds backslashes to quotes in many locations with addslashes(). Unfortunately, this adding has produced output akin to the following.
Every time I refresh my page, this string increases in number of back slashes.
don't
don\'t
don\\'t
don\\\\'t
don\\\\\\\\'t
and so on.
I want to write a function that deletes all these extra back slashes. I have tried
str_replace($text, "\\\\", "");
to no avail.
You may just use:
stripslashes($text);
$text=preg_replace('/\134+/',"\134",$text);
What happens if your actual value happens to include \\ legitimately? For instance, if your content were referring to a Windows-style share reference - \\192.168.1.1\foo. If you blindly strip out any double slashes, you'll strip out ones that are meant to be there, as well.
The "right" answer is really to not add slashes to things that don't need them. You should know whether a given value is already escaped or not (after all, you're the one controlling where every value comes from, and what it's being used for) and only add slashes when you need them.
Related
I want to create hyperlinks to pages on my site but the page address have double quotes within them?
Eg:
the above just links to mysite.com/search.php?q= as I would expect as it is written.
The API returning results allows phrase searches by placing them in double quotes.
Is there a way to escape these within the href tag?
Simple solution: use altenative quotes:
<a href='mysite.com/search.php?q="sales+manager"&l=usa'></a>
This will work fine (the browser will make sure the URL gets properly formatted when a user clicks it), but you should really be urlencoding special characters because there's a whole bunch of stuff that you're not allowed to use in URLs, and some stuff that has a different meaning (in a URL, spaces become +, for instance, so you can't drop in a + and get it to stay that once you parse it. URL magic!).
Have a look at urlencode and use that when generating the link URL server side. This will turn things like spaces into %20, double quotes into %22, etc., and is how you send literal string data from a client to a server.
Yo must encode the quotes "
mysite.com/search.php?q="sales+manager"&l=usa
Is there a way to escape these within the href tag?
Yes, with the escape character. \.
Although, the current state of your code would produce:
effectively breaking the href since you are breaking the string.
What you want, is just:
...
you are considering whether the characters need to be escaped in order to work in your HTML.
however, you should also consider whether they need to be escaped in order to be sound URLs.
to work in your HTML you may do
<a href="mysite.com/search.php?q='sales+manager'&l=usa">.
however, the ' character cannot be in a URL.
"Uniform Resource Locators may only contain the displayable characters in the standard ASCII character set. Nondisplayable characters or characters in the extended ASCII set (128 through 255) are specially encoded."
See here for a list of URL escape codes.
perhaps you want to retain the quotes in the get-request of your URL. in that case, you might want:
<a href="mysite.com/search.php?q=%22sales+manager%22&l=usa">
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.
Original format:
<a href="http://www.example.com/t434234.html" ...>
1. I need to fetch all URLs of this format:
http://www.example.com/t[ANY CHARACTER].html
ANY CHARACTER is where value changes from URL to another. The rest are fixed.
Here is my attempt:
preg_match("#http:\/\/www\.aqarcity\.com\/t[a-zA-Z0-9_]\.html#", $page, $urls);
I get empty results. I don't know where i went wrong...
The problem appears to be that [a-zA-Z0-9_] will only match exactly one character. If you want to match zero or more characters, use [a-zA-Z0-9_]*. For one or more, use [a-zA-Z0-9_]+. For exactly six characters, use [a-zA-Z0-9_]{6}. For e.g. one to six characters, use [a-zA-Z0-9_]{1,6}.
Also note that, since you're using # as the delimiter, you don't need to escape the / characters. As far as I know this will not make your code misbehave, but it'll be easier to read if you remove the backslashes before the slashes.
Finally, please realize that regular expressions are a rather dangerous way to work with HTML. In this case, you may pick up matching URLs from comments, Javascript code, and other things that aren't links. It is literally impossible to correctly parse HTML with unaugmented regular expressions—they don't have the expressive power necessary to do so. I don't know what sorts of HTML parsers are available for PHP, but you may want to look into them.
I have a file on my server that i want to access. The filename is ken\'s book.doc
But in my db, it was stored as ken's book.doc
(I have fixed the backslash issue, but still have problems accessing the previously uploaded files on server.
I used addslashes to add the back slash but it displays it as: ken/'s book.doc (that is a forward slash instead of a backslash.
I have used:
str_replace("'", "\'", $filename);
yet it displays as a forward slash.
How can i fix this?
Thanks
EDIT
Extra Information: I am using the new value as part of a link. that is:
View
If you have a filename that contains a backslash on disk, I would fix that first. Your second problem was appearantly not using mysql_real_escape_string when storing that filename into the database (why it ended up there without backslash).
addslashes btw does not add forward slashes by itself. That part of your story is untrue. And to remove them again you wouldn't need the quirky str_replace call, but just stripslashes.
The actual problem (after your edit) turns out to be a html link. That's simply because browsers have the habit of turning backslashes into forward slashes in urls. To prevent that apply urlencode()
View
This has been driving be crazy, but I can't seem to find an answer. We run a technical knowledge base that will sometimes include Windows samba paths for mapping to network drives.
For example: \\servername\sharename
When we include paths that have two backslashes followed by each other, they are not escaped properly when running 'addslashes'. My expected results would be "\\\\servername\\sharename", however it returns "\\servername\\sharename". Obviously, when running 'stripslashes' later on, the double backslash prefix is only a single slash. I've also tried using a str_replace("\\", "\", $variable); however it returns "\servername\sharename" when I would expect "\\servername\sharename".
So with addslashes, it ignores the first set of double-backslashes and with str_replace it changes the double-backslashes into a single, encoded backslash.
We need to run addslashes and stripslashes for database insertion; using pg_escape_string won't work in our specific case.
This is running on PHP 5.3.1 on Apache.
EDIT: Example Code
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo addslashes($variable);
This returns: In the box labeled Folder type: \\servername\\sharename
EDIT: Example Code #2
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo str_replace('\\', '\', $variable);
This returns: In the box labeled Folder type: \servername\sharename
I'd also like to state that using a single quotes or double-quotes does not give me different results (as you would expect). Using either or both give me the same exact results.
Does anyone have any suggestions on what I can possibly do?
I think I know where is a problem. Just try to run this one:
echo addslashes('\\servername\sharename');
And this one
echo addslashes('\\\\servername\sharename');
PHP escapes double slashes even with single quotes, because it is used to escape single quote.
Ran a test on the problem you described, and the only way I could get the behavior you desired was to couple a conditional with a regex and anticipate the double slashes at the start.
$str = '\\servername\sharename';
if(substr($str,0,1) == '\\'){
//String starts with double backslashes, let's append an escape one.
//Exclaimation used for demonstration purposes.
$str = '\\'.$str;
echo addslashes(preg_replace('#\\\\\\\\#', '!',$str ));
}
This outputs:
!servername\\sharename
While this may not be an outright answer, it does work and illustrates a difference in how the escape character is treated by these two constructs. If used, the ! could easily be replaced with the desired characters using another regex.
This is not a problem with addslashes, it is a problem with the way you are assigning the string to your variable.
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo $variable;
This returns: In the box labeled Folder type: \servername\sharename
This is because the double backslash is interpreted as an escaped backslash. Use this assignment instead.
$variable = 'In the box labeled Folder type: \\\\servername\\sharename';
I've determined, with more testing, that it indeed is with how PHP is handling hard-coded strings. Since hard-coded strings are not what I'm interested in (I was just using them for testing/this example), I created a form with a single text box and a submit button. addslashes would correctly escape the POST'ed data this way.
Doing even more research, I determined that the issue I was experiencing was with how PostgreSQL accepts escaped data. Upon inserting data into a PostgreSQL database, it will remove any escape characters it is given when it actually places the data in the table. Therefore, stripslashes is not required to remove escape characters when pulling the data back out.
This problem stemmed from code migration from PHP 4.1 (with Magic Quotes on) to PHP 5.3 (with Magic Quotes deprecated). In the existing system (PHP4), I don't think we were aware that Magic Quotes were on. Therefore, all POST data was being escaped already and then we were escaping that data again with addslashes before inserting. When it got inserted into PostgreSQL, it would strip one set of slashes and leave the other, therefore requiring us to stripslashes on the way out. Now, with Magic Quotes off, we escape with addslashes but are not required to use stripslashes on the way out.
It was very hard to organize and determine exactly where the problem lay, so I know this answer is a little off to my original question. I do, however, thank everyone who contributed. Having other people sound off on their ideas always helps to make you think on avenues you may not have on your own.