How to remove backslash on json_encode() function?

前端 未结 10 1825
逝去的感伤
逝去的感伤 2020-12-03 04:42

How to remove the (\\)backslash on a string? when using echo json_encode() ?

For example:



        
10条回答
  •  [愿得一人]
    2020-12-03 05:21

    the solution that does work is this:

    $str = preg_replace('/\\\"/',"\"", $str);
    

    However you have to be extremely careful here because you need to make sure that all your values have their quotes escaped (which is generally true anyway, but especially so now that you will be stripping all the escapes from PHP's idiotic (and dysfunctional) "helper" functionality of adding unnecessary backslashes in front of all your object ids and values).

    So, php, by default, double escapes your values that have a quote in them, so if you have a value of My name is "Joe" in your DB, php will bring this back as My name is \\"Joe\\".

    This may or may not be useful to you. If it's not you can then take the extra step of replacing the leading slash there like this:

    $str = preg_replace('/\\\\\"/',"\"", $str);
    

    yeah... it's ugly... but it works.

    You're then left with something that vaguely resembles actual JSON.

提交回复
热议问题