1

Possible Duplicate:
Extract numbers from a string

How can I find a number in a string with PHP? for example :

<?
    $a="Cl4";
?>

i have a string like this 'Cl4' . i wanna if there is a number like '4' in the string give me this number but if there is not a number in the string give me 1 .

Community
  • 1
  • 1

4 Answers4

1
<?php

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

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

    echo get_number('Cl4');

?>
Adam Taylor
  • 4,691
  • 1
  • 37
  • 38
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;
Samuel Cook
  • 16,620
  • 7
  • 50
  • 62
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
Maks3w
  • 6,014
  • 6
  • 37
  • 42
0

Here is a simple function which will extract number from your your string and if number not found it will return 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
?>
Pankaj Khairnar
  • 3,028
  • 3
  • 25
  • 34