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.