可能重复:
从字符串中提取数字
如何使用 PHP 在字符串中查找数字?例如 :
<?
$a="Cl4";
?>
我有一个像这样的字符串 'Cl4' 。我想如果字符串中有像 '4' 这样的数字给我这个数字,但如果字符串中没有数字给我 1 。
<?php
function get_number($input) {
$input = preg_replace('/[^0-9]/', '', $input);
return $input == '' ? '1' : $input;
}
echo get_number('Cl4');
?>
这是一个简单的函数,它将从您的字符串中提取数字,如果找不到数字,它将返回 1
<?php
function parse_number($string) {
preg_match("/[0-9]/",$string,$matches);
return isset($matches[0]) ? $matches[0] : 1;
}
$str = 'CI4';
echo parse_number($str);//Output : 4
$str = 'ABCD';
echo parse_number($str); //Output : 1
?>
$str = 'CI4';
preg_match("/(\d)/",$str,$matches);
echo isset($matches[0]) ? $matches[0] : 1;
$str = 'CIA';
preg_match("/(\d)/",$str,$matches);
echo isset($matches[0]) ? $matches[0] : 1;
$input = "str3ng";
$number = (preg_match("/(\d)/", $input, $matches) ? $matches[0]) : 1; // 3
$input = "str1ng2";
$number = (preg_match_all("/(\d)/", $input, $matches) ? implode($matches) : 1; // 12