用PHP提取字符串中的第一个整数 [英] Extract first integer in a string with PHP

查看:567
本文介绍了用PHP提取字符串中的第一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下字符串:

$strings = array(
    "8.-10. stage",
    "8. stage"
);

我想提取每个字符串的第一个整数,所以它将返回

I would like to extract the first integer of each string, so it would return

8
8

我试图用preg_replace过滤掉数字,但它返回所有整数,我只想要第一个.

I tried to filter out numbers with preg_replace but it returns all integers and I only want the first.

foreach($strings as $string)
{
    echo preg_replace("/[^0-9]/", '',$string);
}

有什么建议吗?

推荐答案

使用正则表达式的便捷(虽然性能不会破纪录)解决方案是:

A convenient (although not record-breaking in performance) solution using regular expressions would be:

$string = "3rd time's a charm";

$filteredNumbers = array_filter(preg_split("/\D+/", $string));
$firstOccurence = reset($filteredNumbers);
echo $firstOccurence; // 3

假设输入中至少有一个数字,这将打印第一个数字.

Assuming that there is at least one number in the input, this is going to print the first one.

非数字字符将被完全忽略,除了它们被认为是分隔数字的事实之外,这意味着第一个数字可以出现在输入中的任何位置(不一定在开头).

Non-digit characters will be completely ignored apart from the fact that they are considered to delimit numbers, which means that the first number can occur at any place inside the input (not necessarily at the beginning).

如果只考虑出现在字符串开头的数字,则不必使用正则表达式:

If you want to only consider a number that occurs at the beginning of the string, regex is not necessary:

echo substr($string, 0, strspn($string, "0123456789"));

这篇关于用PHP提取字符串中的第一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆