-3

I have number '1 out of 023' i want 023 from string and add plus 1 number in 023 so new number will be 024 and string will be '1 out of 024'

i used following code (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);

3 Answers3

1

Just for fun:

$result = array_sum(array_filter(explode(" ", $text), 'is_numeric'));
$text = "1 out of $result";

Based on comment:

$text = '1 out of 23';
$result = array_filter(explode(" ", $text), 'is_numeric');
$text = str_replace($end = end($result), $end+1, $text);

Or:

$text = preg_replace_callback('/[0-9]+$/',
            function ($m) { return ($m[0]+1); }, $text);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Too bad nobody knows what you are talking about. – AbraCadaver Feb 16 '15 at 21:53
  • ok i want i have string `$text = '1 out of 23'; preg_match('/\d+ out of (\d+)/', $text, $matches); $lastnum1 = $matches[1]+1;` new number is 24 now i want add updated number into my previous string '1 out of 24' – qmobile bmc Feb 16 '15 at 22:00
  • @qmobilebmc Last attempt to understand what you want: You want to grab the first and the last number in your string, add them together and updated the string with the new number at the end? (Few examples: `2 out of 10` -> `2 out of 12`; or `1 out of 30` -> `1 out of 31` ?) – Rizier123 Feb 16 '15 at 22:02
  • @ Rizier123 i want last number from string '1 out of 23 ' last string is 23 .....added +1 in 23 now got 24. at last i want update this number into my string '1 out of 23' (old code) --------------> '1 out of 24' (new updated) – qmobile bmc Feb 16 '15 at 22:07
  • Not reindexed. Fixed. – AbraCadaver Feb 16 '15 at 22:19
1

I think this is what you want:

(Here I just use preg_match_all() to get all numbers from your string. After this I use end() to get the last number from the string and then I simply use str_replace() to replace the old number with the incremented one)

<?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);

?>

Output:

1 out of 23
1 out of 24
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • @qmobilebmc You're welcome! But please be more specific next time! (See also: http://stackoverflow.com/help/how-to-ask) – Rizier123 Feb 16 '15 at 22:15
0

You could use an array since it seems like you're looking for the last word and not necessarily the last 3 characters (e.g. what if it were 1 out of 2345).

$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;
rick6
  • 467
  • 3
  • 8