php正则:匹配(),{},[]小括号,大括号,中括号里面的内容

php正则:匹配(),{},[]小括号,大括号,中括号里面的内容

比如有一段字符:

$s='60c8
 
{"code":"200","message":"success","data":[{"_id":"780521","time":1476768196,"position":{"long":108.90415,"lat":35.25623},"speed":495.677952,"anum":"B6552","atype":"A321","atypename":"Airbus A321-231","angle":"198","vspeed":"-576","device":"9d26b827eb566225","onground":"0","updatetime":1476768198,"height":3581.4,"fnum":"CSN3722 ","alert":"0","spi":"0","squawk":"1107","emergency":"0"}]}';

我要匹配,{}括号里面的内容,单独拿出来。

preg_match('/(?:\{)(.*)(?:\})/i', $s, $match);
var_dump($match);

说明:

PHP使用正则表达式提取字符串中尖括号<>、小括号()、中括号[]、大括号{}中的字符示例,需要的朋友可以参考下

$str="你好<我>(爱)[北京]{天安门}";
echo f1($str); //返回你好
echo f2($str); //返回我
echo f3($str); //返回爱
echo f4($str); //返回北京
echo f5($str); //返回天安门
function f1($str)
{
$result = array();
preg_match_all("/^(.*)(?:<)/i",$str, $result);
return $result[1][0];
}
 
function f2($str)
{
$result = array();
preg_match_all("/(?:<)(.*)(?:>)/i",$str, $result);
return $result[1][0];
}
function f3($str)
{
$result = array();
preg_match_all("/(?:\()(.*)(?:\))/i",$str, $result);
return $result[1][0];
}
function f4($str)
{
$result = array();
preg_match_all("/(?:\[)(.*)(?:\])/i",$str, $result);
return $result[1][0];
}
function f5($str)
{
$result = array();
preg_match_all("/(?:\{)(.*)(?:\})/i",$str, $result);
return $result[1][0];
}

PS: (?:字符) 表示不捕获这个字符。貌似PHP不支持将字符换成括号。 
否则的话可以将环视给嵌套进去,就可以循环匹配了。 
PS2:环视:(?!) (?=) (?<!) (?<=) 
有小于号的在右侧匹配,没有的在左侧匹配。感叹号表示不等,等于号表示相等。 
PS3:都过了验证器的验证,验证器见参考资料。 

posted @ 2019-06-10 16:47  大数据老司机  阅读(4581)  评论(0编辑  收藏  举报