如何在PHP中找到字符串中的数字? 例如:
<?
$a="Cl4";
?>
我有一个像'Cl4'这样的字符串。我想如果字符串中有一个像'4'这样的数字给我这个数字,但如果字符串中没有数字给我1。
答案 0 :(得分:1)
<?php
function get_number($input) {
$input = preg_replace('/[^0-9]/', '', $input);
return $input == '' ? '1' : $input;
}
echo get_number('Cl4');
?>
答案 1 :(得分:0)
$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;
答案 2 :(得分:0)
$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
答案 3 :(得分:0)
这是一个简单函数,它会从你的字符串中提取数字,如果找不到数字,它将返回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
?>