Add double back slash to single in php - php

I have searched a lot and tried javascript replace() function and str_replace,addslashes , strip slashes as well but i am not getting the right output.
This is what im doing:
str_replace("\\","\\\\", "C:wamp\www\desi\uploads\artist\bg\9.jpg";
THe output i am getting is:
C:wampwwwÞsiuploads\A rtist\B g .jpg
Then another way i tried:
var clean= "<?php echo str_replace("\\","#",LINKCONSTANT); ?>".replace("#","\\");
Still not working any idea ?

the problem isn't solvable by using str_replace like that because the string in double quotes will have the slashes processed by PHP as escape sequences. Using str_replace like this isn't going to solve the problem of PHP (or javascript) handling string escapes - once you have got a backslash into a string it will stay there quite faithfully.
However string constants will work in single quotes as follows:
'C:wamp\www\desi\uploads\artist\bg\9.jpg'
but as pointed out elsewhere the directory separator in windows is internally handled as either "/" or "\" so just use the "/" (for api calls) and you'll be fine.
If you wish to output a string that is safe to be parsed by javascript then do:
echo "var str = ".json_encode('C:wamp\www\desi\uploads\artist\bg\9.jpg').";";
which will output in a javascript compatible way:
var str = "C:wamp\\www\\desi\\uploads\\artist\\bg\\9.jpg";

What are you going to achieve? Replace the single \ by \\?
Please note, that
"\\"
denotes a string of a single \. This is due to the fact, that \ prefixes an escape sequence in used inside of "...":
\r -> Return
\t -> Tabular
\n -> Newline
Since \ has this special meaning, you need to write \\ to denote a single \ inside of "....".
Thus, this will set $resultString to C:wamp\\www\\desi\\uploads\\artist\\bg\\9.jpg:
$sourceString = "C:wamp\www\desi\uploads\artist\bg\9.jpg";
$resultString = str_replace( "\\", "\\\\", $sourceString );

Related

PHP function for removing and adding back in \'?

I have a search form for finding restaurants. I got it handling apostrophe's just fine for the actual search, but when they're passed as \' into Javascript for mapping it's killing my maps.
Example:
xml_searchresults.php?cityID=1&type=1&searchTerm=Sonny\'s Real Bit BBQ
For a simple fix, in PHP I'm trying to go from:
$searchTerm = "Sonny\'s Real Bit BBQ" (in the original PHP file)
Then replace the \' with [slashapostrophe]:
$searchTerm = "Sonny[slashapostrophe]s Real Bit BBQ" (to be fed to javascript)
and then replace the [slashapostrophe] back with \':
$searchTerm = "Sonny\'s Real Bit BBQ" (in the PHP generated XML map marker file)
I tried str_replace but the quotes and slashes confuse it. Thanks!
php function addslashes() to quote string with '\' and stripslashes() to remove extra '\' symbols ( to unquote quoted string)
You are looking for stripslashes(): http://php.net/manual/en/function.stripslashes.php

Saving source code from HTML textarea to file

I am saving C++ code from a textarea of an HTML form using PHP.
The problem is if my code is like below,
printf("%d\n");
printf("%d\n");
the code that is saved to the file is like this:
printf(\"%d\\n\");\nprintf(\"%d\\n\");
I want the original code to be saved in the file. If I use,
$sourceCode = str_replace('\n',"\n", $sourceCode);
$sourceCode = str_replace('\"',"\"", $sourceCode);
the result is like below (saved in the file):
printf("%d\
");printf("%d\
");
It is clear that replacing \n in the source code replaces all the HTML created \n along with the \n that user gave as input (the original text). The only difference is user's input has an additional \ before the \n, that is \\n.
How can I resolve the problem such that only the implicit escape characters will be replaced, but the explicit escape characters, that the user wrote himself, will not be changed?
As mentioned by KenB, we need to see the PHP code that you are using to process the form input.
Processing Form Input
It looks to me like addslashes has been used on the form input.
If you are doing that in your code, don't. This is not the proper way to process form input. Instead, you should use the correct function (such as htmlspecialchars or mysqli_real_escape_string) to escape the input before you use it. Read about addslashes.
If you are using an older version of PHP where magic_quotes_gpc is on by default, then you should fix that. Read about 'Disabling Magic Quotes'.
Stripping Out the Slashes
If you have no control over the code that is adding the slashes, then you can remove them with a simple PHP function called stripslashes.
$sourceCode = stripslashes($sourceCode);
Read about stripslashes.
Understanding Escape Sequences
Your str_replace code shows a lack of understanding about escape sequences and/or a lack of understanding about single vs double quotes.
In the following code, a literal \n is replaced with a line break. With the double quotes, PHP interprets the \n as an escape sequence rather than a literal string.
$sourceCode = str_replace('\n',"\n", $sourceCode);
What you want is to replace a literal \\n with a literal \n. Note that to specify a literal backslash it must be doubled; hence the triple backslash you see below.
$sourceCode = str_replace('\\\n', '\n', $sourceCode);
And although this next line accomplishes what you wanted...
$sourceCode = str_replace('\"',"\"", $sourceCode);
...it could have been written differently. The following code is easier to read, saves you having to escape the literal ", and doesn't require PHP to interpret the string.
$sourceCode = str_replace('\"', '"', $sourceCode);
I've given the above code as examples to explain how PHP interprets escapes sequences, but don't use them. Either avoid adding the slashes in the first place or strip them using the proper function, as explained in the first part of this answer.
Read more about escape sequences and quoting strings.
The Literal \n Between Lines
I'm not sure what you are doing to add the literal \n between the lines. We'd need to see your code. But to remove it after the fact, you could try the following
$sourceCode = str_replace(';\n', ";\n", $sourceCode);
Of course, then you'd likely need to correct other C++ end-of-line sequences. So it is better to not add it in the first place.

How do I let PHP echo "\n" as plain-text for javascript and not have the "\n" create a new line?

PHP is echoing JavaScript (I'm using the jQuery library) something like this:
echo 'var users = $("#add").val().split("\n");';
However, the \n is creating a line break in what the echoed script looks like, and therefore breaking the JavaScript. Is there a way to circumvent this?
Many thanks!
The \n is an escape sequence meaning newline. Backslashes are the beginning of escape sequences, to output a backslash then write \\. So you want \\n. Other useful escape sequences include the quote: use \" to put a quote into the string instead of ending the string.
echo "var users = $(\"#add\").val().split(\"\\n\");";
Not sure If you looking for this
echo "<script>alert('Line1\\\\nThis still in Line1')</script>";

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.

Replacing backslash with another symbol in PHP

Been struggling with replacing a backslash by another symbol such as '.-.' just to indicate the position of backslashes as I could not send a string such as 'C\xampp\etc.' through url as GET variable so I thought I'd first replace the backslashes in that string by another symbol, then send through url, and then replace them back to backslashes in the PHP file that handles it. Though would there be a better way to send such strings through url? Because when I try a script such as:
$tmp_name = preg_replace("\", ".-.", $_FILES['uploadfile']['tmp_name']);
It turns out into a php error as \ is also used as delimiter..
Could anyone help me out on this?
Thanks in advance!
Btw, if I'd be able to send a full array through url, this whole problem would be solved, but I don't think it's possible?
The regex used in preg_replace should be enclosed in a pair of delimiter and also Try using \\\ instead of \ as:
$tmp_name = preg_replace("{\\\}", ".-.", $_FILES['uploadfile']['tmp_name']);
EDIT:
To reverse the substitution you can do:
$str = preg_replace('{\.-\.}',"\\",$str);
You need to escape the . to match a literal dot.
use urlencode()/urldecode().
echo urlencode('C:\xampp\etc'); // C%3A%5Cxampp%5Cetc
BTW: This sounds like a huge security flaw (sending absolute paths by request)
PS: preg_replace() is for regular expressions. Try str_replace() next time.
Btw, if I'd be able to send a full array through url, this whole problem would be solved, but I don't think it's possible?
That's easy. PHP:
$url = 'http://example.com/?array=' . urlencode(serialize($array)); // html
$array = unserialize($_GET['array']); // server side
Or Javascript:
url = "http://example.com/?array=" + encodeURIComponent(JSON.stringify(array)); // client
$array = json_decode($_GET['array']); // server
(for Javascript you'll have to look up whether encodeURIComponent is correct, and you need the official JSON library as well)
If you're not using a regular expression (which you're not), you should use str_replace instead:
$tmp_name = str_replace('\\', '.-.', $_FILES['...']);
Note that you have to escape the \ with another \ (otherwise it'd escape the following ').
As for the delimiter error - regular expressions need to be enclosed in delimeters, for example /foo/ (/ is the delimiter, foo is the pattern). But, again, there's no need for you to use or worry about regexps

Categories