简体   繁体   中英

Counting and returning Matches with Regular Expression

Consider the following values:

$format = ',0';        // Thousand separators ON, no decimal places 
$format = '0';         // Thousand separators OFF, no decimal places
$format = '0.000';     // Thousand separators OFF, 3 decimal places
$format = ',0.0';      // Thousand separators ON, 1 decimal place
  1. The first thing to do is see if $format is prefixed with a ','. This tells me that thousand separators are enabled.
  2. Secondly, I must then see how many zeros there are after the first one. Eg, the following would be 2 decimal places '0.00' etc.

I have managed to match the expression (this was not very hard), but what I would like to do is extract the individual matches so I can know whether or not there was a ',' found, and how many zeros there are etc...

This is what I have so far:

preg_match_all('/^\,?[0]?[\.]?([0])+?$/',$value['Field_Format'],$matches);

I would use a different regex and put the sub-results into named groups:

if (preg_match(
    '/^
    (?P<thousands>,)? # Optional thousands separator
    0                 # Mandatory 0
    (?:               # Optional group:
     (?P<decimal>\.)  # Decimal separator
     (?P<digits>0+)   # followed by one or more zeroes
    )?                # (optional)
    $                 # End of string/x', 
    $subject, $regs)) {
    $thousands = $regs['thousands'];
    $decimal = $regs['decimal'];
    $digits = $regs['digits'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM