Search code examples
phppreg-match

Check if string ends with number and get the number if true


How can i check if a string ends with a number and if true, push the number to an array (for example)? I know how to check if a string ends with a number, I solved it like this:

$mystring = "t123";

$ret = preg_match("/t[0-9+]/", $mystring);
if ($ret == true)
{
    echo "preg_match <br>";
    //Now get the number
}
else
{
    echo "no match <br>";
}

Let's assume all strings start with the letter t and are composited with a number e.g. t1,t224, t353253 ...

But how can I cut this number out if there is one? In my code example there is 123 at the end of the string, how can I cut it out and for example push it to an array with array_push?


Solution

  • $number = preg_replace("/^t(\d+)$/", "$1", $mystring);
    if (is_numeric($number)) {
        //push
    }
    

    This should give you the trailing number. Simply check that if it's numeric, push it to your array

    Sample: https://3v4l.org/lYk99

    EDIT:

    Just realize that this doesn't work with string like this t123t225. If you need to support this case, use this pattern instead: /^t.*?(\d+)$/. This means it tries to capture whatever ends with the number, ignoring everything in between t and number, and has to start with t.

    Sample: https://3v4l.org/tJgYu