PHP 查找字符串中最后一个数字的位置和值


PHP Find position and value of last Digit in string

$string = "hello 31 84 1 546 today 77 is 4 good";

如何获得最后一个"4"的位置?

如何获取值"4"?

你的问题不清楚,但我认为这就是你要找的?

$string = "hello 31 84 1 546 today 77 is 4 good";
if(preg_match_all('/'d+/', $string, $numbers))
    $lastnum = end($numbers[0]);
  1. 匹配字符串中的所有分组整数
  2. 将它们放入数组中。
  3. 数组的最后一个元素是句子中的最后一个数字。

编辑:

正如@Michael在评论中所说:

也许,如果 OP 需要,请从 多位数数字 - 例如,如果它以 49 好结尾,则 substr() 得到 9 在技术上是最后一个数字,而不是 49,因为这将是 返回。虽然不清楚的问题。

答案如下:

$s1 = "hello 31 84 1 546 today 77 is 894 good";
if(preg_match_all('/'d+/', $s1, $numbers)){
    $lastFullNum =      end($numbers[0]);               //eg. "894"
    $lastDigit =        substr($lastFullNum, -1);       //eg. "4"
    $lastDigitPos =     strrpos($s1, $lastDigit, 0);    //eg. "32"
}
您可以使用

preg_match来获取最后一位数字,将"last"定义为"从那里找不到更多数字的那个点",即"直到字符串($)末尾都是非数字(''D)":

preg_match('#(''d+)''D*$#', $string, $gregs);

现在$gregs[1]包含最后一个数字s。(如果您只想要最后一个,请省略"+")。如果字符串包含回车符,则可能需要多行修饰符。

要获取数字的偏移量,您需要strrpos

$offset = strrpos($string, $gregs[1]);

或者,您可以使用preg_match的PREG_OFFSET_CAPTURE选项:

if (false !== preg_match('#(''d+)''D*$#', $string, $gregs, PREG_OFFSET_CAPTURE)) {
    list ($digit, $offset) = $gregs[1];
}

数组示例;

<?php
  $s1 = "hello 31 84 1 546 today 77 is 894 good";
  $array = explode(' ',$s1);
  echo end($array) . '<br />';
  echo prev($array) . '<br />';
?>