php - 2 identical string showing different lengths

1.2k Views Asked by At

I am having a problem comparing 2 identical strings. The first string is retrieved from a database and the other hard coded.

The string is { "name":"John", "age":30, "car":null }.

I've first run this code and the database string has a length of 79 character and the hard coded string has a length of 39 characters.

echo '<pre>';var_dump($json_data);echo '</pre>';
echo '<pre>';var_dump('{ "name":"John", "age":30, "car":null }');echo '</pre>';

After some searching it was suggested to use bin2hex() and using that i've narrowed it down to the " character.

Replacing the database value with a " and running the following code outputs

2671756f743b for the database value and 22 for the hard coded value.

echo bin2hex($json_data)."<br>";
echo bin2hex('"')."<br>";

What is the correct way to get both values to compare using strcmp() as based on the comparison i will be doing other code.

2

There are 2 best solutions below

0
On BEST ANSWER

Thanks to @Mark Baker, I had to html_entity_decode() the database value and now both values match.

0
On

Had a similar issue where 2 strings appeared to be the same, managed to figure out an issue on one of the strings the following way.

  • json_encode() the string, this would result in a null
  • run json_last_error_msg() to get any encoding errors. Got Malformed UTF-8 characters, possibly incorrectly encoded
  • run utf8_encode() on the string did the trick to fix encoding errors.