从 PHP 字符串中提取整数:如何只获取数字?
使用 preg_match() 提取第一个数字
最可靠且灵活的方法是使用正则表达式配合 preg_match() 函数。
<?php
// 示例字符串
$strings = [
"Заказ № 98765",
"Сумма: 1500 рублей",
"ID: 42",
"Результат: 0 ошибок",
"Цена: 1234 руб.",
"Артикул #5678-90",
"Код 123, цена 456"
];
foreach ($strings as $str) {
if (preg_match('/\d+/', $str, $matches)) {
$number = (int)$matches[0];
echo "Исходная строка: \"$str\" - Извлечено число: $number\n";
} else {
echo "Исходная строка: \"$str\" - Число не найдено\n";
}
}
?>
提取所有数字(如果有多个数字)
如果字符串包含多个数字,可以使用 preg_match_all() 提取所有数字:
<?php
$str = "Код 123, цена 456";
preg_match_all('/\d+/', $str, $matches);
$numbers = array_map('intval', $matches[0]);
print_r($numbers); // 输出: Array ( [0] => 123 [1] => 456 )
?>
使用 filter_var() 过滤数字字符
另一种简单方法适用于只取连续数字序列的场景:
<?php
$str = "Сумма: 1500 рублей";
$result = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
$number = (int)$result; // 1500
echo $number; // 输出 1500
?>
完整示例,附带备注
<?php
/**
* 从字符串中提取第一个整数
* @param string $input 输入字符串
* @return int|null 找到整数则返回,否则返回 null
*/
function extractFirstNumber($input) {
if (preg_match('/\d+/', $input, $matches)) {
return (int)$matches[0];
}
return null;
}
// 测试
$testStrings = [
"Заказ № 98765",
"Сумма: 1500 рублей",
"ID: 42",
"Результат: 0 ошибок"
];
foreach ($testStrings as $s) {
$num = extractFirstNumber($s);
echo "Строка: \"$s\" - Извлечено: " . ($num !== null ? $num : "null") . "\n";
}
?>
对于您提供的示例,以上方法都能正确提取整数(98765、1500、42、0)。preg_match('/\d+/', ...) 是最通用和推荐的方式,因为它不受字符串中非数字字符位置的影响。