Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp type for number 0

Tags:

regex

php

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?

like image 942
David Jaw Hpan Avatar asked Aug 13 '15 10:08

David Jaw Hpan


People also ask

What is regex for numbers?

The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.

What does the regex 0 9 ]+ do?

In this case, [0-9]+ matches one or more digits. A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier). This regex matches any numeric substring (of digits 0 to 9) of the input.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.


1 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.)

like image 135
mario Avatar answered Sep 21 '22 17:09

mario