PHP: -IF- Ask if the field has letters

3

Good morning everyone!

I came across something that is making me renege and I still can not find the solution:

My code enters a field which if it has LETTERS I cancel it.

That is:

                        $valor= "1A8CF4D2414E000094136783";
                        #FILTRADO CAMPO 1


                        if( preg_match('/^[A-Z]+$/', $valor) )
                        { 

                            echo('Lectura posee letras.');
                            $valor = "0";

                        } else {
                            echo('Lectura NO posee letras.');
                        }

The problem is that it always returns the value of else even if the condition is green. What can be wrong?

Thank you very much !!

    
asked by Jona Gregov 04.10.2017 в 21:28
source

4 answers

2

Your problem is that preg_match returns an integer, not a boolean.

  

preg_match () returns 1 if pattern matches the given subject, 0 if   no, or FALSE if an error occurred.

     

Warning This function can return the Boolean value FALSE, but   You can also return a non-Boolean value that evaluates to FALSE.

All of the following, is considered false, and therefore falls through the else:

  

the integer 0 (zero)
  the float 0.0 (zero)
  the empty string value, and the string "0"
  an array with zero elements

In your case, you are asking if the string only contains letters, which is false. then it returns 0, which is false. You should check the regex, one that could work for you:

[A-Z]+
    
answered by 04.10.2017 / 21:45
source
2

Over here there are people with a lot more experience than me in Regex. But I will try to answer you.

You are asking if it matches:

/^    Empieza por
[A-Z] Un rango de A a Z
+     Una o más coincidencias
$/    Termina por

So it's only accepting strings of type KJBFKGJBKSBGBJKVJV .

If you delete the delimiters ^ and $ you will search for any match without explicitly taking into account that you must start or end with the indicated characters. Which would solve the problem.

$valor="1A8CF4D2414E000094136783";
#FILTRADO CAMPO 1

if(preg_match('/[A-Za-z]+/', $valor)) {
    echo 'Lectura posee letras.';
    $valor="0";
}
else {
    echo 'Lectura NO posee letras.';
}
    
answered by 04.10.2017 в 21:45
2
$valor= "1A8CF4D2414E000094136783";

if ( preg_match('/[A-Z]/i', $valor) )
{
    echo('Lectura posee letras.');
} else {
    echo('Lectura NO posee letras.');
}

The /i avoids case sensitivity.

    
answered by 04.10.2017 в 21:40
0

try this solution

$valor= "1A8CF4D2414E000094136783";
                    #FILTRADO CAMPO 1

if(!preg_match('/^[0-9]+$/', $valor) )
{ 

 echo('Lectura posee letras.');
 $valor = "0";

 } else {
     echo('Lectura NO posee letras.');
 }
    
answered by 04.10.2017 в 21:43