Home » Php » php – Regexp type for number 0

php – Regexp type for number 0

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to 0 to 9 any number in input fields,so i check filter_var as below

<?php
$res['pno'] = filter_var($cond['pno'],FILTER_VALIDATE_REGEXP,
//check valid phone no
array('options'=>array('regexp'=>'/^0+[0-9]*$/')))?true:false;                
?>

It is ok when type any number ,But type 0 only ,it return false so how to check it to return true if i type 0 only?

How to&Answers:

The regexp itself was fine already.

Your actual issue is this:

 ?true:false

When filter_var with the regex succeeds, it will return a string of just "0".

  • Now if ?: evaluates that in boolean context, then your final expression will simply be false.

  • So wrap your filter_var() result check with strlen() or is_string.

     = is_string(filter_var(…, …, …)) ? true : false;
    

    (Yes, the ?true:false is highly redundant then.)

Answer:

Maybe try:

if ($res['pno']!==false){
    // !== operator is important
    // because it checks value AND type of constant
    // string '0' is equal false if You checks only value
}

Answer:

Try this: check condition with !==false like following:

$cond['pno']="0";
$res['pno'] = filter_var($cond['pno'],FILTER_VALIDATE_REGEXP,
array('options'=>array('regexp'=>'/^0+[0-9]*$/')))!==false?true:false;                
var_dump($res['pno']);
$cond['pno']="01";
$res['pno'] = filter_var($cond['pno'],FILTER_VALIDATE_REGEXP,
array('options'=>array('regexp'=>'/^0+[0-9]*$/')))!==false?true:false;                
var_dump($res['pno']);
$cond['pno']="a";
$res['pno'] = filter_var($cond['pno'],FILTER_VALIDATE_REGEXP,
array('options'=>array('regexp'=>'/^0+[0-9]*$/')))!==false?true:false;                
var_dump($res['pno']);

Output

boolean true

boolean true

boolean false

Answer:

Because the PHP is a loosely typed language ( comparison is done not on the type of, but only on the value of a variable by default ), condition that returns string "0" is evaluated as empty and therefore else statement is executed. To check if value is empty and not a number use empty( $num ) && !is_numeric( $num ), for example:

$res['pno'] = filter_var( $cond['pno'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp'=>'/^0+[0-9]*$/' ) ) );
$res['pno'] = !( empty( $res['pno'] ) && !is_numeric( $res['pno'] ) );