PHP json_decode - how to use with escape quotes string? - php

I have this string:
{\"sub\":\"value\"}
How I can use json_decode on this string?
When I try do it in that way:
$text = '{\"sub\":\"value\"}';
$json = json_decode($text, true);
var_dump($json);
I got NULL as result.
I know, I can use something like that:
$text = str_replace('\"', '"', $text);
But it also return null, because my original string is more extensive.
Real json_string you can found here: https://www.olx.pl/oferta/praca/praca-w-sklepie-internetowym-CID4-IDP2Wy2.html
It start from: window.__PRERENDERED_STATE__= " and end at the end of this code line.
Thanks for your help.

According to PHP: Strings - Manual escape sequences will not be expanded when they occur in single quoted strings.
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings
That means your string $text = '{\"sub\":\"value\"}'; will be treated as string with separate \ and " characters, which is invalid JSON string.
You need to use double quotes around string $text = "{\"sub\":\"value\"}"; in that case \" will be expanded, therefore you will get a valid JSON string.

Related

explode and substr_count not work with "\n\n"

Hi guys why i can't explode or count character with "\n\n" in my string?
$input = 'sv_privateClientsForClients\\0\\sv_pure\\0\n0 0 0 0 999 \"DarkGhost\"\"spectator\"\n\n0 0 0 0 999 \"MaximuM\"\"spectator\"\n\n",';
$str = substr($input, strpos($input, "sv_pure") + 11, -7);
$x = explode('\n\n', $str); //not work
$c = substr_count($str,"\n\n"); // not work
$input = 'sv_privateClientsForClients\\0\\sv_pure\\0\n0 0 0 0 999 \"DarkGhost\"\"spectator\"\n\n0 0 0 0 999 \"MaximuM\"\"spectator\"\n\n",';
$str = substr($input, strpos($input, "sv_pure") + 11, -7);
$x = explode('\n\n', $str);
$c = substr_count($str,'\n\n'); //changed double quotes to single quotes
Try to replace '\n' with a "ABC" using str_replace() function and then explode string with "ABC"
Do you want a pair of newline characters, or do you literally want the string \n\n in the output? The answer hinges on the answer to that question, but in either case by far the most important thing you can do is be consistent with the style of quotes you use.
PHP strings can be in single quotes (''), or in double quotes ("") as well as a couple of other formats that we won't get into for the sake of simplicity. Single quotes and double quotes are not the same:
Double quote strings support the inclusion of a number of control characters (\n for newlines, \t for tabs, etc), while single quote strings support almost no control characters. If you want a newline in a single quote string you have to literally put a newline into the string.
Double quote strings support variable substitution (if you put a named variable in the string then the contents of the named variable will be substituted when you echo the string out).
The fact that your code is using single-quoted strings for some things and double-quoted strings for others means that your strings are inconsistent. "\n\n" will not match '\n\n' because they are not the same thing.
If you intend for \n\n to mean a pair of newlines then you should simply just use double-quoted strings throughout.
If you intend for \n\n to mean the literal string '\n\n' then you can either use single-quoted strings throughout, or you could use the escape sequence \\ which tells PHP that the next character is not a control character but a literal backslash. To get \n\n with a double-quoted string you need to enter it into your code as "\\n\\n"

different output from same function with same parameters

I am confused with following string function
echo strlen("l\n2"); //give 3 in output
where as
echo strlen('l\n2'); //give 4 in output
can anybody explain why ?
Because when you use single quotes (' '), PHP does not expand the \n as a single new line character whereas in double quotes (" "), \n translates to the new line character (ie. a single character) thus giving 3 characters
Taken from PHP's String Documentation: http://php.net/manual/en/language.types.string.php
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
\n is not parsed as a newline character when the string is wrapped in single quotes. Instead, it is treated as a literal \ followed by n.

Regular Expression to find \"

What's the regular expression to find \"
I think it's this: '/\\"/' but I need to use it on a really large dataset so need to make sure this is correct.
I need to replace it with " so my code is : $data = preg_replace('/\\"/', '"', $data)
Is that correct?
For matching backslashes you need to 'double-escape' them, so you have four \ at the end:
$data = preg_replace('/\\\\"/', '"', $data);
Why you need 4 \: PHP parses a string \\" as \" and RegEx interprets this as " since in RegEx you don't need to escape ". So it wont match \". \\\\" will be parsed as \\" which will be interpreted as \" by RegEx.
A backslash does not need to be escaped in either a single-quoted string or a regular expression, unless the following character is a character that can be escaped (such as the backslash itself).
A double quote does not need to be escaped and cannot be escaped in a single-quoted string. In a regular expression it doesn't have to be either, but it can be.
That means \\ in both a single-quoted string and a regular expression becomes \, while \" in a single-quoted string remains \", while in a regular expression it becomes ".
However, in PHP you can only create a regular expression from a string, so you have to escape twice.
In other words...
Original string String processed Regexp processed
'/\"/' /\"/ "
'/\\"/' /\"/ "
'/\\\"/' /\\"/ \"
'/\\\\"/' /\\"/ \"
'/\\\\\"/' /\\\"/ \"
'/\\\\\\"/' /\\\"/ \"
'/\\\\\\\"/' /\\\\"/ \\"
Bonus backslash
In a double-quoted string, of course, the " does need to be escaped, so...
"/\"/" /"/ "
"/\\"/" syntax error
"/\\\"/" /\"/ "
"/\\\\"/" syntax error
"/\\\\\"/" /\\"/ \"
"/\\\\\\"/" syntax error
"/\\\\\\\"/" /\\\"/ \"
"/\\\\\\\\"/" syntax error
"/\\\\\\\\\"/" /\\\\"/ \\"
I think you should probably go for preg_replace("/\\\\\\\"/", "\"", $data) just to be on the safeconfusing side.
As long as you mean the literal string \", matching for those characters in a regular expression requires:
\\"
So, you'd use /\\\\"/ as the pattern parameter in a preg_* function.
(You only need to escape the backslash - since PHP handles backslashes in single and double-quotes strings as a special character, you need to escape them twice.)
Is this all you need to match? If so, I'd recommend just using str_replace():
$string = str_replace('\\"', '"', $string);
For a simple search/replace of literal characters like this, an iterative string function like str_replace() will be faster than a regular expression.
this one is correct.
preg_replace('/\\\"/', '"', $data);
http://sandbox.phpcode.eu/g/1283c.php
In PHP, backslashes have special meaning. You can therefore represent a literal backslash as either of the following: \\\ or \\\\. The alternative method is to use a character class: [\\].
Refer to the section labeled "Note" here:
http://www.php.net/manual/en/regexp.reference.escape.php
Would this not work just as well for your data?
str_replace('\\"','"',$data);
$result = preg_replace('/\\\\"/i', '"', $subject);

php single and double quotes

//remove line breaks
function safeEmail($string) {
return preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
}
/*** example usage 1***/
$from = 'HTML Email\r\t\n';
/*** example usage 2***/
$from = "HTML Email\r\t\n";
if(strlen($from) < 100)
{
$from = safeEmail($from);
echo $from;
}
1 returns HTML Email\r\t\n while
2 returns HTML Email
what's with the quotes?
As per the PHP Documentation
Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
In other words, double quoted strings expand variables and escape sequences for special characters. Single quoted strings don't.
So in example1, with the single quoted string, the string is exactly as you see it. Slashes and all.
But in example2, rather than ending with the string \r\t\n, it ends with a carriage return, a tab and then a new line. In other words the escape sequences for special characters are expanded.
with single quotes in PHP those special characters as \n \r \t... doesn't work as expected.
According to the docs:
To specify a literal single quote, escape it with a backslash (\). To specify a literal
backslash, double it (\\). All other instances of backslash will be treated as a literal
backslash: this means that the other escape sequences you might be used to, such as \r or
\n, will be output literally as specified rather than having any special meaning.

Is there an equivalent of C#'s verbatim string literals in PHP?

I know I can create a verbatim string literal in C# by using the # symbol. For example, the usual
String path = "C:\\MyDocs\\myText.txt";
can also be re-written as
String path = #"C:\MyDocs\myText.txt";
In this way, the string literal isn't cluttered with escape characters and makes it much more readable.
What I would like to know is whether PHP also has an equivalent or do I have to manually escape the string myself?
$path = 'C:\MyDocs\myText.txt';
" double quotes allow for all sorts of special character sequences, ' single quotes are verbatim (there's only some fine print about escaping ' and escaping an escape \).
Even single-quoted strings in PHP have the need for escaping at least literal single-quotes and literal backslashes:
$str = 'Single quotes won\'t help me \ avoid escapes or save a tree';
The only non-parsed solution for PHP is to use nowdocs. This requires you use PHP 5.3.
$str = <<<'EOD'
I mustn't quote verbatim text \
maybe in the version next
EOD;

Categories