Check if line ends with number and gets number if true

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

$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>";
}

Suppose that all lines begin with a letter tand are composed with a number, for example. t1, t224, t353253...

But how can I cut out this number, if any? In my example code, there is 123at the end of the line, how can I cut it and, for example, click on an array with array_push?

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

. , ,

: https://3v4l.org/lYk99

EDIT:

, , t123t225. , : /^t.*?(\d+)$/. , , , t , t.

: https://3v4l.org/tJgYu

+2

-, ( , ), lookbehind match array :

$test = 't12345';

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

    $result = $matches[0];

    echo($result);
}
+2

preg_match, , : ([0-9]+)

, :

$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>";
}
+1

Add one more parameter to the function preg_match, and I would like to suggest some other regular expression in order to get the number from the last line.

$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
)
+1
source

All Articles