Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Invalid cast of a string in an object with JSON and regex in PHP

Here are some sample code that should lead to the same result. Once in JavaScript and Perl where it is understandable and once in PHP which leads to problems.

All of this takes place in a complete scenario in various components of a framework. Therefore the first definition of $a = ['a\b'] is mandatory.

The result $r is just a control example for an external parser process.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!env node
const a = ['a\b'];
console.debug(a); // [ 'a\b' ]

const j = JSON.stringify(a);
console.debug(j); // ["a\b"]

let s = 'foo';
s = s.replace(/foo/, j);
console.debug(s); // ["a\b"]

const r = JSON.parse(s);
console.debug(r); // [ 'a\b' ]
#!env php
<?php
$a = ['a\b'];
print_r($a); print "\n"; // Array([0] => a\b)

$j = json_encode($a);
print_r($j); print "\n"; // ["a\\b"]

$s = 'foo';
$s =  preg_replace('/foo/', $j, $s);
print_r($s); print "\n"; // ["a\b"] ⚡️

$r = json_decode($s);
print_r($r); print "\n"; // Array ([0] => a)
#!env perl
useJSON;
use Data::Dumper;

my $a = ['a\b'];
print Dumper($a);

my $j = encode_json($a);
print Dumper($j);

my $s = 'foo';
$s =~ s/foo/$j/;
print Dumper($s);

my $r = decode_json($s);
print Dumper($r);

The result is also valid:

$VAR1 = [
           'away'
         ];
$VAR1 = '["a\\\\b"]';
$VAR1 = '["a\\\\b"]';
$VAR1 = [
           'away'
         ];

>Solution :

In simplest terms, you need to escape the \ for use in the second parameter:

$s =  preg_replace('/foo/', str_replace( '\\', '\\\\', $j), $s);

Although, you should also read the details of the replacement parameter from https://www.php.net/manual/en/function.preg-replace.php to understand other pitfalls.

The replacement parameter isn’t just a string it’s an instruction set for regex replacement meaning there are special chars to be considered for regex purposes versus your JSON needs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading