Reqular exp to get the last number from a string

Hello to all
how can I get a number (positive number) from a string if the string syntax is as follows:

t_def_type_id_2
t_def_type_id_22
t_def_type_id_334

so in the first line I want to get 1, and in the second I want to get 22, and in the third line I want to get 334 using preg_match_all or any other sutable php function

+4
source share
10 answers

You can use regex

\d+$ 

with preg_match

+5
source

if there is only one number in the string, just use \d+

+2
source

Try the following:

 preg_match('/^\w+(\d+)$/U', $string, $match); $value = (int) $match[1]; 
+2
source

you can use

 str_replace('t_def_type_id_',''); 
+1
source

what about the following code:

^ [\ d] + (\ d +) $

+1
source

You can use preg_replace() :

 $defTypeID = preg_replace("/^(.*?)(\d+)$/", "$2", $defTypeIDString); 
0
source
 $string = "t_def_type_id_2 t_def_type_id_22 t_def_type_id_334"; preg_match_all("#t_def_type_id_([0-9]+)#is", $string, $matches); $matches = $matches[1]; print_r($matches); 

Result:

 Array ( [0] => 2 [1] => 22 [2] => 334 ) 
0
source

If this is always the last thing on your line, then using the banal function of the string function is possible and looks a little more complicated:

 $num = ltrim(strrchr($string, "_"), "_"); 
0
source

you can use

 ^\w+(\d+)$ 

but I have not tested

0
source

Here is my alternative solution.

 $number = array_pop(explode('_', $string)); 
0
source

Source: https://habr.com/ru/post/1345726/


All Articles