Black
Black

Reputation: 20252

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?

Upvotes: 4

Views: 735

Answers (4)

Lionel Chan
Lionel Chan

Reputation: 8069

$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

Upvotes: 2

Chetan Ameta
Chetan Ameta

Reputation: 7896

Add one more parameter in preg_match function and i would like to suggest some other regex for the same to get number from last of any string.

$array = array();
$mystring = "t123";

$ret = preg_match("#(\d+)$#", $mystring, $matches);


array_push($array, $matches[0]);

$mystring = "t58658";

$ret = preg_match("#(\d+)$#", $mystring, $matches);

array_push($array, $matches[0]);

$mystring = "this is test string 85";

$ret = preg_match("#(\d+)$#", $mystring, $matches);

array_push($array, $matches[0]);

print_r($array);

output

Array
(
    [0] => 123
    [1] => 58658
    [2] => 85
)

Upvotes: 1

SierraOscar
SierraOscar

Reputation: 17637

first, your regex is a bit wrong (might be a typo) - but to answer your question you can use a lookbehind and a match array like so:

$test = 't12345';

if(preg_match('/(?<=t)(\d+)/', $test, $matches)){

    $result = $matches[0];

    echo($result);
}

Upvotes: 2

Daniel Dudas
Daniel Dudas

Reputation: 3002

You should use the 3rd param from preg_match to get the matches and there should be the number and change your regex like this: ([0-9]+)

So the code should look like this:

$mystring = "t123";

$ret = preg_match("/([0-9]+)/", $mystring, $matches);
if ($ret == true)
{
    print_r($matches); //here you will have an array of matches. get last one if you want last number from array.
    echo "prag_match <br>";
}
else
{
    echo "no match <br>";
}

Upvotes: 1

Related Questions