PHP convert double quote string to single quote string

I know this question has been asked here many times. But these solutions were not useful to me. Today I ran into this problem very badly.

// Case 1 $str = 'Test \300'; // Single Quoted String echo json_encode(utf8_encode($str)) // output: Test \\300 // Case 2 $str = "Test \300"; // Double Quoted String echo json_encode(utf8_encode($str)) // output: Test \u00c0 

I need the output of case 2, and I have a single quoted variable $ str. This variable is populated from parsing XML strings. And this XML string is saved in a txt file.

(Here \ 300 is the character encoding for À (Latin Charactor), and I cannot control it.)

Please do not give me a solution for a more static string

Thank you in advance

+6
source share
2 answers

This will do:

 $string = '\300'; $string = preg_replace_callback('/\\\\\d{1,3}/', function (array $match) { return pack('C', octdec($match[0])); }, $string); 

It matches any backslash sequence followed by up to three numbers, and converts that number from an octal number to a binary string. Which has the same result as "\300" .

Note that this will not work the same for shielded screens; that is, "\\300" will result in the literal \300 , while the above code converts it.

If you want all possible double-quoted string rules to be respected without re-evaluating them manually, it is best to simply eval("return \"$string\"") , but this also has a few caveats.

+2
source

May you look for it

 $str = 'Test \300'; // Single Quoted String echo json_encode(stripslashes($str)); // output: Test \\300 
-3
source

Source: https://habr.com/ru/post/986823/


All Articles