How to detect numbers in a string with PHP

Programmer.zip picture Programmer.zip · Sep 8, 2013 · Viewed 14.9k times · Source

This is the test.php file:

<?php

$string = 'A string with no numbers';

for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    $message_keyword = in_array($char, range(0,9)) ? 'includes' : 'desn\'t include';
}

// output
echo sprintf('This variable %s number(s)', codeStyle($message_keyword));

// function
function codeStyle($string) {
    return '<span style="background-color: #eee; font-weight: bold;">' . $string . '</span>';
}

?>

It splits the string character by character and check if the character is a number or not.

Problem: It's output is always "This variable includes number(s)". Please help me to find the reason. TIP: When I change range(0,9) to range(1,9) It works correctly (But it can't detect 0).

Answer

hek2mgl picture hek2mgl · Sep 8, 2013

Use preg_match():

if (preg_match('~[0-9]+~', $string)) {
    echo 'string with numbers';
}

Althought you should not use it, as it is much slower than preg_match() I will explain why your original code is not working:

A non numerical character in the string when compared to a number (in_array() does that internally) would be evaluated as 0 what is a number. Check this example:

var_dump('A' == 0); // -> bool(true)
var_dump(in_array('A', array(0)); // -> bool(true)

Correct would be to use is_numeric() here:

$keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
    if(is_numeric($string[$i]))  {
       $keyword = 'includes';
       break;
    }
}

Or use the string representations of the numbers:

$keyword = 'doesn\'t include';
// the numbers as stings
$numbers = array('0', '1', '2', /* ..., */ '9');

for ($i = 0; $i <= strlen($string)-1; $i++) {
    if(in_array($string[$i], $numbers)){
       $keyword = 'includes';
       break;
    }
}