我有数字"023中的1",我想要字符串中的023,并在023中加1,这样新的数字将是024,字符串将是"024中的一"
我使用了以下代码(stackoverflow)
$text = '1 out of 23';
preg_match('/'d+ out of ('d+)/', $text, $matches);
$lastnum1 = $matches[1];
$text = "1 out of 23";
$words = explode(" ",$text);
$lastnum = (int)array_pop($words);
我想这就是你想要的:
(在这里,我只使用preg_match_all()
从字符串中获取所有数字。之后,我使用end()
从字符串中获得最后一个数字,然后简单地使用str_replace()
用递增的数字替换旧数字)
<?php
echo $text = "1 out of 23" . "<br />";
preg_match_all("!'d+!", $text, $matches);
$number = end($matches[0]);
echo $text = str_replace($number, ++$number, $text);
?>
输出:
1 out of 23
1 out of 24
只是为了好玩:
$result = array_sum(array_filter(explode(" ", $text), 'is_numeric'));
$text = "1 out of $result";
基于评论:
$text = '1 out of 23';
$result = array_filter(explode(" ", $text), 'is_numeric');
$text = str_replace($end = end($result), $end+1, $text);
或者:
$text = preg_replace_callback('/[0-9]+$/',
function ($m) { return ($m[0]+1); }, $text);
您可以使用数组,因为它看起来像是在寻找最后一个单词,而不一定是最后3个字符(例如,如果它是2345中的1个)。
$text = '1 out of 23';
$highest_number = end(explode(" ",$text));
//If you want to to add 1
$highest_number++;
//Or if you want to create a new variable
$new_highest_number = $highest_number + 1;