Ben H
Ben H

Reputation: 512

How to get value from text string in PHP

I have the following string:

"{\"ttl\": null\054 \"card_id\": \"np\"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg"

I can tidy this using strip slashes so it becomes:

"{"ttl": null, "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg"

I need to get the value where np is however I am unsure how to do this. Is it best to remove the trailing text and address it as JSON or am I best using another method?

the string in question does contain the wrapping " "

Current Code:

echo stripslashes($VCIDcookie); 

$string = stripslashes($VCIDcookie);

output of $string: "{"ttl": null54 "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg"

$string = explode('}', $string);

$json = json_decode($string[0] .'}');
echo $json->card_id;

Updated Code - I have used trim() to remove the wrapping quotation marks so the string doesn't have them but I am still not getting the np output:

$string = trim($VCIDcookie,'"');
$string = stripslashes($string);
echo $string;
$string = explode('}', $string);

$json = json_decode($string[0] .'}');
echo $json->card_id;

Upvotes: 0

Views: 56

Answers (1)

Vincent Decaux
Vincent Decaux

Reputation: 10714

Try this :

$string = '{"ttl": null, "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg';
$string = explode('.', $string);

$json = json_decode($string[0]);
echo $json->card_id;

Care : I suppose ttl or card_id don't have "." in their values.

Or, to avoid problems with "." :

$string = '{"ttl": null, "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg';
$string = explode('}', $string);

$json = json_decode($string[0] .'}');
echo $json->card_id;

Upvotes: 3

Related Questions