$testString = "76,2-2; 75,1-2.22; 79,2-3.6;";
如何才能在-和之前获得第一个值;具有特定的选择?
我尝试了多次爆炸,但这似乎对性能不好。
例如,76个期望值2,75个期望值2.22,79个期望值3.6。
PS:是的,在ID号之前有空格。
发布于 2016-03-10 21:11:44
您可以使用这个regex:
$str = '76,2-2; 75,1-2.22; 79,2-3.6;'
preg_match_all('/(\d+),\d+-(\d+(?:\.\d+)?);/', $str, $m);
$output = array_combine ( $m[1], $m[2] );
print_r($output);
输出:
Array
(
[76] => 2
[75] => 2.22
[79] => 3.6
)
结果数组有您要寻找的所有键值对。您可以查找以下任何值:
echo $output['76']
2
echo $output['75']
2.22
echo $output['79']
3.6
发布于 2016-03-10 21:46:18
anubhava的方法很棒,特别是如果您想要处理字符串一次并多次访问数组,那么这似乎更简单:
$find = 75;
preg_match("/$find,\d+-([^;]+)/", $testString, $match);
echo $match[1]; // if found it will always be $match[1]
https://stackoverflow.com/questions/35927199
复制相似问题