从以特定方式格式化的字符串中轻松提取数据


Easily extract data from string formatted a specific way

获取这样格式化的字符串的简单方法是什么:

c:7|bn:99

能够很容易地使用那根绳子吗?所以,如果我想得到c:后面的数字,我怎么能轻易得到呢。同样,bn后面的数字:?

您可以使用preg_match()函数,也可以使用两次explode()函数(第一次使用|分隔符,第二次使用:分隔符(。

示例#1:

<?php
if( preg_match( '/^c:('d+)'|bn:('d+)$/', $sString, $aMatches ) )
{
  print_r( $aMatches );
}
?>

示例2:

<?php
$aPairs = explode('|', $sString ); // you have two elements in $aPairs
foreach( $aParis as $sPair )
{
  print_r( explode(':', $sPair ) );
}
?>
$arr = array();
$str = "c:7|bn:99";
$tmp1 = explode('|', $str);
foreach($tmp1 as $val)
{
   $tmp2 = explode(':', $val);
   $arr[$tmp2[0]] = $tmp2[1]; 
}
//print ur array
print_r($arr);
//accessing specifc value
echo $arr['c']." ".$arr['bn'];

试试这个:

$string = 'c:7|bn:99';
preg_match('/'Ac:([0-9]+)'|bn:([0-9]+)'z/', $string, $matches);
var_dump($matches);

如果c&bn不是动态的:

var_dump(sscanf("c:7|bn:99","c:%d|bn:%d"));
array(2) {
  [0]=>
  int(7)
  [1]=>
  int(99)
}