Check if there is a number in a string

3

I need to do several validations on my form, and one of them is to check if the name you typed contains number somewhere in the string is at the beginning middle or end, I already tried to use is_numeric only worked for numbers, not a mixture of numbers with letters.

What could I do?

    
asked by anonymous 21.09.2016 / 19:47

4 answers

6

Filter_var with FILTER_SANITIZE_NUMBER_INT

One way to check if string contains at least one number, without using regular expression (which is usually slower), is by using the filter_var function.

See:

var_dump(filter_var('teste', FILTER_SANITIZE_NUMBER_INT)); // ''

var_dump(filter_var('teste1', FILTER_SANITIZE_NUMBER_INT)); // '1'

The FILTER_SANITIZE_NUMBER_INT flag is responsible for removing all non-numeric characters from the expression and returning only the numbers. So we can know if it has numbers in string checking if it did not return an empty% co_.

Example:

filter_var($valor, FILTER_SANITIZE_NUMBER_INT)) !== ''

We have to take care , as PHP's blessed compares string to a '0' == false expression. So that's why I used the true comparison. Another important detail is that if you pass ! == '' on the first parameter of array (with filter_var ) it will return FILTER_SANITIZE_NUMBER_INT instead of false .

This could cause a "Boolean clutter".

So thinking about the point of view that I've gone through, the smart thing to do is:

Combining '' with FILTER_SANTIZE_NUMBER_INT

Since the return from is_numeric will only return numbers, then we can use the FILTER_SANTIZE_NUMBER_INT function to know if the result of is_numeric is a number or not, which is present in the string .

function contains_number($string) {
   return is_numeric(filter_var($string, FILTER_SANITIZE_NUMBER_INT));
}
    
21.09.2016 / 19:49
6

Study about regular expressions and have a look at preg_match ()

if( preg_match('/\d+/', $nome)>0 ){
   echo 'Seu nome tem algum numero';
}

This regex will detect if it has one or more numbers anywhere in the string.

    
21.09.2016 / 19:51
3

Here are some other alternatives.

filter_var

You can use the filter_var function to filter only numbers (and% + ) using the - filter, if the filtering fails, the result is FILTER_SANITIZE_NUMBER_INT :

function encontrouNumeros($string) {
    return (filter_var($string, FILTER_SANITIZE_NUMBER_INT) === '' ? false : true);
}

var_dump(encontrouNumeros("stack")); // bool(false)
var_dump(encontrouNumeros("st4ck")); // bool(true)

For floating point use false .

FILTER_SANITIZE_NUMBER_FLOAT

How to suggested by Wallace Maxters , you can also use the ctype_digit function, is returned ctype_digit if all the characters in the string are numeric, true otherwise.

To check if a string contains numbers, check character in loop :

function encontrouNumeros2($string) {
    $indice = 0;
    while ($indice < strlen($string)) {
        if (ctype_digit($string[$indice]) === true) return true;
        $indice++;
    }
    return false;
}

var_dump(encontrouNumeros2("stack")); // bool(false)
var_dump(encontrouNumeros2("st4ck")); // bool(true)

false

The function strpbrk searches the string for one of the characters which are in a set, returns a string starting from the found character, or strpbrk if none of the characters in the set is found:

function encontrouNumeros3($string) {
    return strpbrk($string, '0123456789') !== false;
}

var_dump(encontrouNumeros3("stack")); // bool(false)
var_dump(encontrouNumeros3("st4ck")); // bool(true)
    
21.09.2016 / 20:12
0

The question does not specify whether you want to get the position of what to find as a numeric, so by focusing on the snippet that says you only need to find numeric characters, you would do something like this.

function NumbersOnly($str, $float = false)
{
    $r = '';
    if ($float) {
        $r = '.';
        $str = str_replace(',', $r, $str);
    }
    return preg_replace('#[^0-9'.$r.']#', '', mb_convert_kana($str, 'n'));
}

$str = 'foo2';

if (!empty(NumbersOnly($str))) {
    echo 'Encontrou números';
} else {
    echo 'NÃO encontrou números';
}

Zenkaku numeric character care

The filter_var() function does not consider ZenKaku 1234567890 characters which are different from 1234567890 ASCII characters. Notice how visually the size is different.

If you want something more consistent that detects the Zenkaku characters, the above example is more secure.

A test with the 4 versions, including those that were posted in the other answers:

function phpfilter($str) {
    return filter_var($str, FILTER_SANITIZE_NUMBER_INT);
}
function encontrouNumeros($string) {
    return (filter_var($string, FILTER_SANITIZE_NUMBER_INT) === '' ? false : true);
}
function NumbersOnly($str, $float = false)
{
    $r = '';
    if ($float) {
        $r = '.';
        $str = str_replace(',', $r, $str);
    }
    return preg_replace('#[^0-9'.$r.']#', '', mb_convert_kana($str, 'n'));
}


$str = 'foo3'; // testando com zenkaku
//$str = 'foo'; // sem número
//$str = 'foo3'; // número ascii

if (!empty(phpfilter($str))) {
    echo 'Encontrou números';
} else {
    echo 'NÃO encontrou números';
}
echo '<br>';
if (encontrouNumeros($str)) {
    echo 'Encontrou números';
} else {
    echo 'NÃO encontrou números';
}
echo '<br>';
if (!empty(NumbersOnly($str))) {
    echo 'Encontrou números';
} else {
    echo 'NÃO encontrou números';
}

echo '<br>';
if( preg_match('/\d+/', $str)>0 ){
    echo 'Encontrou números';
} else {
    echo 'NÃO encontrou números';
}

Alternative with strpbrk ()

As posted in another answer, we have this function serves very well with a much cleaner code:

function encontrouNumeros3($string) {
    return strpbrk($string, '0123456789') !== false;
}

var_dump(encontrouNumeros3("st4ack"));

However, you should again beware of zenkaku characters. To do this, hit add them to the function.

function encontrouNumeros3($string) {
    return strpbrk($string, '01234567891234567890') !== false;
}

var_dump(encontrouNumeros3("st4ack")); // retorna true

The difference between the function of the first example NumbersOnly() and strpbrk() is that one sanitiza and another returns boolean if it finds any of the characters specified in the second parameter. Choose what's convenient for you.

Finishing

Something that may be the simplest to focus the question:

if (preg_match('/\d+/', mb_convert_kana($str, 'n')) > 0) {
    echo 'Encontrou números';
} else {
    echo 'NÃO encontrou números';
}

I did not perform performance testing. But the idea is to sanitize with mb_convert_kana() and apply any other solution. Just see which one is faster.

    
11.10.2016 / 06:32