我在023'中有数字#1;我希望023来自字符串,并在023中添加加1号码,因此新号码将为024,字符串将为024' 1
我使用了以下代码(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);
答案 0 :(得分:1)
只是为了好玩:
$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);
答案 1 :(得分:1)
我认为这就是你想要的:
(这里我只使用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
答案 2 :(得分:0)
您可以使用数组,因为您似乎在寻找最后一个单词而不一定是最后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;