2015-04-01 119 views
0

這裏是我的例子字符串的獲得價值「:」和「」

"{"id":128,"order":128,"active":"1","name":"\" 

現在我需要得到‘128’ - ID參數。因此它是「:」和「,」之間的第一個值。

我嘗試過preg_match和不同的正則表達式,但我只是不擅長正則表達式。也許有人會知道如何做到這一點?

$id = preg_match('/:(,*?)\,/s', $content, $matches); 
+1

爲什麼不用'json_decode'? – hjpotter92 2015-04-01 13:55:58

+1

它看起來像那個字符串是JSON。不要用正則表達式自己解析它,而是使用json_decode函數將它解碼爲可以訪問的結構。 http://php.net/manual/en/function.json-decode.php – 2015-04-01 13:56:11

+0

嘗試'preg_match('/(?<=:)[^,] *(?=,)/',$ content,$ matches );' – 2015-04-01 14:03:07

回答

1

下面是一個示例代碼的第一:後得到的數量使用一個正則表達式:

$re = "/(?<=\\:)[0-9]+/"; 
$str = "\"{\"id\":128,\"order\":128,\"active\":\"1\",\"name\":\"\""; 
preg_match($re, $str, $matches); 
print $matches[0]; 

這裏是關於TutorialsPoint的示例程序。

只是關於這個正則表達式的一個小細節(?<=\\:)[0-9]+:幸運的是它使用固定寬度look-behind that PHP supports

0
<?php 


$txt='"{"id":128,"order":128,"active":"1","name":"\\"'; 

$re1='.*?'; # Non-greedy match on filler 
$re2='(\\d+)'; # Integer Number 1 
$re3='.*?'; # Non-greedy match on filler 
$re4='(\\d+)'; # Integer Number 2 
$re5='.*?'; # Non-greedy match on filler 
$re6='(\\d+)'; # Integer Number 3 

    if ($c=preg_match_all ("/".$re1.$re2.$re3.$re4.$re5.$re6."/is",$txt, $matches)) 
    { 
    $int1=$matches[1][0]; 
    $int2=$matches[2][0]; 
    $int3=$matches[3][0]; 
    print "($int1) ($int2) ($int3) \n"; 
    } 

    ?> 
+0

這不是okey,結果是空。 – 2015-04-01 14:02:15