Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect numbers in a string with PHP

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).

like image 855
Programmer.zip Avatar asked Sep 08 '13 12:09

Programmer.zip


2 Answers

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;
    }
}
like image 95
hek2mgl Avatar answered Oct 16 '22 07:10

hek2mgl


You can just use regexp :

$message_keyword = preg_match('/\d/', $string) ? 'includes' : 'desn\'t include';
like image 44
OneOfOne Avatar answered Oct 16 '22 08:10

OneOfOne