我試圖得到一些特定的值了以下字符串:如何從中得到字符串?
{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"
我想「Toyota
」出來的那個。該字符串是隨機生成的,因此它可能是Benz
或Pontiac
。
我試圖得到一些特定的值了以下字符串:如何從中得到字符串?
{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"
我想「Toyota
」出來的那個。該字符串是隨機生成的,因此它可能是Benz
或Pontiac
。
不能確定這個瘋狂的字符串是什麼,但如果你已經準確地顯示的格式,這將提取您的字符串後:
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = array_filter(
explode(',',
preg_replace(
array('/"/', '/{/', '/:/', '"car"'),
array('', ',', '', ''),
$string
)
)
);
print_r($string);
// Output: Array ([1] => Toyota [2] => honda [3] => BMW [4] => Hyundai)
...如果,相反,這是隻是一個可怕的類型0,這應該是JSON,使用json_decode
:
$string = '[{"car":"Toyota"},{"car":"honda"},{"car":"BMW"},{"car":"Hyundai"}]'; // <-- valid JSON
$data = json_decode($string, true);
print_r($data);
// Output: Array ([0] => Array ([car] => Toyota) [1] => Array ([car] => honda) [2] => Array ([car] => BMW) [3] => Array ([car] => Hyundai))
文檔
preg_replace
- http://php.net/manual/en/function.preg-replace.phparray_filter
- http://php.net/manual/en/function.array-filter.phpexplode
- http://php.net/manual/en/function.explode.phpjson_decode
- http://php.net/manual/en/function.json-decode.php雖然這看起來像一個腐敗的一塊JSON的,我會說你可以得到的第一輛車與爆炸()。
$string = '{"car":"Toyota"{"car":"honda"{"car":"BMW{"car":"Hyundai"';
$string = explode("{", $string);
$firstcar = $string[1]; //your string starts with {, so $string[0] would be empty
$firstcar = explode(":", $firstcar);
$caryouarelookingfor = $firstcar[1]; // [0] would be 'car', [1] will be 'Toyota'
echo $caryouarelookingfor // output: "Toyota"
但是,正如在評論中也提到,該字符串看起來像一個腐敗一塊JSON的,所以也許你要修復這個字符串的建設。 :)
編輯:代碼中的錯字,如第一評論中所述。
這種方法非常脆弱,輸出是「豐田」(注意引號)。 – 2012-08-03 19:34:13
你想獲得第一輛車?還是所有的汽車? – 2012-08-03 19:15:05
這應該是一些腐敗的JSON? – Daniel 2012-08-03 19:15:36
這幾乎是JSON。它最初是否是JSON?如果是這樣,它是否已損壞,你是否做了一些替換,或者你是否錯誤地將問題輸入錯了? – 2012-08-03 19:15:42