Php 获取字符串中最后一个逗号之前的数字

Php 获取字符串中最后一个逗号之前的数字,php,Php,我有一个数字可变的字符串,用逗号分隔: $num = 15.514,6.23,9.15 我可以使用以下方法获取最后一个值: $last = substr($num, strrpos($num, ",") + 1); // 9.15 如何获取最后一个逗号(6.23)之前的数字?数字的大小可能会有所不同,因此我必须确保它得到数字,无论它有多少位数 $split = explode(',', $num); // splits the string at each comma // first o

我有一个数字可变的字符串,用逗号分隔:

$num = 15.514,6.23,9.15
我可以使用以下方法获取最后一个值:

$last = substr($num, strrpos($num, ",") + 1); // 9.15
如何获取最后一个逗号(6.23)之前的数字?数字的大小可能会有所不同,因此我必须确保它得到数字,无论它有多少位数

$split = explode(',', $num); // splits the string at each comma

// first option
$secondLast = $split[count($split) - 2];

// second option
end($split); // gets the pointer to the last array element
$secondLast = prev($split); // moves the pointer back one entry

速度差别不大,所以你可以使用你更喜欢的一个。

你可以使用正则表达式得到你想要的结果,正则表达式使用量词的自然贪婪性来达到最后一个逗号:

$result = preg_replace('~.*(?<![^,])([^,]*),.*~', '$1', $str);
$arr=explode(',',$num)$val=$arr[计数($arr)-2]
$parts = str_getcsv($str);
array_pop($parts);
$result = end($parts);