2012-11-24 37 views
1

可能重复:
Extract numbers from a string如何在PHP中查找字符串中的数字?

如何找到在PHP的字符串是多少? 例如:

<? 
    $a="Cl4"; 
?> 

我有一个这样的字符串'Cl4'。我想如果在字符串中有一个像'4'的数字给我这个数字,但是如果字符串中没有数字给我1。

+3

http://stackoverflow.com/questions/6278296/extract-numbers-from-a-string – jeremy

+1

http://stackoverflow.com/questions/6278296/extract-numbers-from-a-string 这可能有所帮助。 –

+0

@Nile :)几乎在同一时间 –

回答

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; 
1
<?php 

    function get_number($input) { 
     $input = preg_replace('/[^0-9]/', '', $input); 

     return $input == '' ? '1' : $input; 
    } 

    echo get_number('Cl4'); 

?> 
+0

我有另一个问题:D。我想用PHP解决一个方程。例如:'a 2 = b 3'。 我想找到a,b的最慢整数值。你可以帮我吗 ? –

+0

@hassanzanjani,这是另一个问题。 – saji89

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 
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 
?>