簡體   English   中英

reqular exp從字符串中獲取最后一個數字

[英]reqular exp to get last number from string

大家好
如果字符串語法如下,我如何從字符串中獲取數字(正數):

t_def_type_id_2
t_def_type_id_22
t_def_type_id_334

所以,在第一個字符串中我想要得到1,在第二個字符串中我想要得到22而在第三個字符串中我希望得到334使用preg_match_all或任何其他可變的php函數

你可以使用正則表達式

\d+$

preg_match

如果字符串中只有一個數字,只需使用\\d+

嘗試這個:

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

您可以使用

str_replace('t_def_type_id_','');

下面的代碼怎么樣:

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

你可以使用preg_replace()

$defTypeID = preg_replace("/^(.*?)(\d+)$/", "$2", $defTypeIDString);
$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);

結果:

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

如果它始終是你的字符串中的最后一件事,那么使用平庸的字符串函數方法是可能的,看起來有點緊湊:

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

你可以用

^\w+(\d+)$

但我沒有測試

這是我的替代解決方案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM