簡體   English   中英

獲取字符串中的最后一個整數

[英]Get last whole number in a string

我需要在包含多個整數的字符串中隔離最新出現的 integer 。

如何為$lastnum1獲得23而不是1

$text = "1 out of 23";
$lastnum1 = $this->getEval(eregi_replace("[^* out of]", '', $text));

你可以這樣做:

$text = "1 out of 23";
if(preg_match_all('/\d+/', $text, $numbers))
    $lastnum = end($numbers[0]);
$text = "1 out of 23";
$ex = explode(' ',$text);
$last = end($ex);

如果你想確定最后一個是數字

if (is_numeric(end($ex))) {
    $last = end($ex);
} 

另一種方法:

$text = "1 out of 23";
preg_match('/(\d+)\D*$/', $text, $m);
$lastnum = $m[1];

這將匹配字符串中的最后一個數字,即使它后面跟着非數字。

使用preg_match將值提取到$matches

preg_match("/([0-9]+) out of ([0-9]+)/", $text, $matches);
$text = '1 out of 23';
preg_match('/\d+ out of (\d+)/', $text, $matches);
$lastnum1 = $matches[1];

如果格式相同,為什么不分解字符串並轉換最后一個?

<?php
$text = "1 out of 23";
$words = explode(" ",$text);
$lastnum = (int)array_pop($words);

如果您無法預測輸入字符串的格式,則可以使用preg_match() ,如果字符串格式可預測,則可以使用sscanf()

代碼:(演示

$text = "1 out of 23";

echo preg_match('/\d+(?=\D*$)/', $text, $m) ? $m[0] : '';
echo "\n";
echo sscanf($text, '%*d out of %d')[0];

echo "\n--- \n";

$text = "1 out of 23 more";

echo preg_match('/\d+(?=\D*$)/', $text, $m) ? $m[0] : '';
echo "\n";
echo sscanf($text, '%*d out of %d')[0];

兩個輸入字符串上的所有兩種技術都返回23

在正則表達式中, \d表示數字字符, \D表示非數字字符。

使用sscanf()%d捕獲一個或多個數字字符, %*d匹配但不捕獲一個或多個數字字符。

暫無
暫無

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

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