如何查找和保存字符串中出现的所有模式


How to find and save all occurrences of pattern within a string

 $testString = "76,2-2; 75,1-2.22; 79,2-3.6;";

如何获取具有特定选择的 ; 之后和之前的第一个值?

我尝试了多次爆炸,但似乎对性能不利。

例如,对于76的期望值2,对于

75的期望值2.22,对于79的期望值3.6。

PS:是的,ID号前有空格。

您可以使用此正则表达式:

$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

> Anubhava的方法很棒,特别是如果你想处理一次字符串并多次访问数组,但这似乎更简单:

 $find = 75; 
 preg_match("/$find,'d+-([^;]+)/", $testString, $match);
 echo $match[1];  // if found it will always be $match[1]