Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert double quoted string to single quoted string

I know this question asked here many times.But That solutions are not useful for me. I am facing this problem very badly today.

// 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 want case 2's output and I have single quoted $str variable. This variable is filled from XML string parsing . And that XML string is saved in txt file.

(Here \300 is encoding of À (latin Charactor) character and I can't control it.)

Please Don't give me solution for above static string

Thanks in advance

like image 412
Paresh Thummar Avatar asked May 08 '15 12:05

Paresh Thummar


1 Answers

This'll do:

$string = '\300';

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

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

Note that this will not work exactly the same for escaped escapes; i.e. "\\300" will result in a literal \300 while the above code will convert it.

If you want all the possible rules of double quoted strings followed without reimplementing them by hand, your best bet is to simply eval("return \"$string\""), but that has a number of caveats too.

like image 105
deceze Avatar answered Oct 13 '22 01:10

deceze