2015-04-01 122 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