How to treat duplicated backslash in json

Asked

Viewed 441 times

-2

What is the best alternative to remove forms placed by the user?

Example through the data received by the user create a json

{
"tags": "\\\u00E7"
}

Obviously json will not read dust is duplicated, it cannot identify which Unicode character is.

What is the best way to treat this, so that it receives only one backslash, regardless of how many users put in form?

  • How not? Using echo json_decode('{"tags": "\u00E7" }')->tags; results in ç, which is correct ("\u{00E7}" === json_decode('{"tags": "\u00E7" }')->tags; is 1).

  • If you take an example where there are several does not work : example $text = '{"tags": "Anima u00e7 u00F5Es"}'; echo json_decode($text)->tags;

  • It doesn’t work because it’s incorrectly escaped, every \\ is a \. For he must have only the \u00E7 and then it should be 6x \ + \00F5Es. Your problem is time to format JSON, this is not present in your question, so there is no solution.

  • @Gabriel, what if you make one str_replace() to remove all those that come? Would this help you? If yes, I can send you an example of the function.

  • You can use echo json_encode(['tags' => '/\ção']); will result in the {"tags":"\/\\\u00e7\u00e3o"}, formatted correctly. Remember that you must be using UTF-8.

  • @Jaksonfischer yes, it would help, a preg_replace would be more useful , but I could not make the regular expression

  • @Gabriel, answered. I ask that if the question is useful, mark it as correct please.

Show 2 more comments

1 answer

-1


As requested in your comment, follow an example of substitution with the str_replace().

$var = "C\o\i\s\a";

//$replace = str_replace('\', '/', $var);

echo str_replace('\\', '', $var)

//Saída: Coisa.

Note that:

When using the \ to be replaced, we will have to add a \ additional, so that PHP understands that it should look for this \ and that she is not part of your code.

The function str_replace() has the function to replace values.

The parameters for its use are:

str_replace("busca", "troca", "conteúdo")

Read about the str_replace() in php.net.

Follows a functional example in phpfiddle.

  • was most useful preg_replace('/( ) 1+/', '$1', $Object);

  • So this didn’t solve?

  • 1

    I solved with preg_replace

Browser other questions tagged

You are not signed in. Login or sign up in order to post.