Regexp type for number 0

I want 0 to 9 numbers in the 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; ?> 

This is normal when you enter any number, but only type 0, it returns false , and how to check it to return true if I type 0 only?

+7
php regex
source share
4 answers

The regexp kernel is already excellent.

Your current issue:

  ?true:false 

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

  • Now, if ?: Evaluates this in a boolean context, your final expression will simply be false .

  • So, end the filter_var () result check with strlen() or is_string .,

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

    (Yes ?true:false has redundant redundancy.)

+9
source share

Perhaps 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 } 
+4
source share

Try the following: check the condition with !==false as follows:

 $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']); 

Exit

 boolean true boolean true boolean false 
+1
source share

Since PHP is a freely typed language (the comparison is not performed by type, but only by the value of the default variable), the condition that returns the string "0" is evaluated as empty , and therefore the else statement is executed. To check if a value is empty, 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'] ) ); 
+1
source share

All Articles