13

我怎样才能得到23而不是1for $lastnum1

$text = "1 out of 23";
$lastnum1 = $this->getEval(eregi_replace("[^* out of]", '', $text));
4

6 回答 6

28

你可以这样做:

$text = "1 out of 23";
if(preg_match_all('/\d+/', $text, $numbers))
    $lastnum = end($numbers[0]);
于 2012-09-25T19:11:26.663 回答
3
$text = "1 out of 23";
$ex = explode(' ',$text);
$last = end($ex);

如果你想确定最后一个是数字

if (is_numeric(end($ex))) {
    $last = end($ex);
} 
于 2012-09-25T19:10:53.343 回答
2

另一种方法:

$text = "1 out of 23";
preg_match('/(\d+)\D*$/', $text, $m);
$lastnum = $m[1];

这将匹配字符串中的最后一个数字,即使它后面跟着非数字。

于 2012-09-28T11:38:34.720 回答
1

用于preg_match将值提取到$matches

preg_match("/([0-9]+) out of ([0-9]+)/", $text, $matches);
于 2012-09-25T19:11:35.173 回答
1
$text = '1 out of 23';
preg_match('/\d+ out of (\d+)/', $text, $matches);
$lastnum1 = $matches[1];
于 2012-09-25T19:11:55.220 回答
1

如果格式相同,为什么不分解字符串并转换最后一个?

<?php
$text = "1 out of 23";
$words = explode(" ",$text);
$lastnum = (int)array_pop($words);
于 2012-09-25T19:12:12.677 回答