Still learning regular expression! My percentage regular expression (not respecting the 100 limit):
^(?<int>[1-9][0-9]*|[0])(?<dec>\.[0-9]+)?\%?$
This should allow:
[1-9]start with a number different from 0. Percentage like “004.34” is not allowed.[0-9]*…followed by any digit in between 0 and 9|[0]or start with a single 0
… capturing this group as “int” group. Then:
(?<dec>\.[0-9]+)?an optional group, where a point is allowed only when is followed by at least one digit between 0 and 9. I don’t want people to input i.e. “33.”
Assuming I’m right, testing with:
preg_match('/^(?<int>[1-9][0-9]*|[0])(?<dec>\.[0-9]+)?\%?$/i', '0.32%', $result);
Gives me this result, which is actually correct, but:
Array
(
[0] => 0.32%
[int] => 0
[1] => 0
[dec] => .32
[2] => .32
)
how can avoid capturing the percentage “%” sign (in $result[0])?
It’s pretty simple really. Just change your regex to this:
(Remove
\%?$from matching).If you want to make sure that the % sign is there, but don’t want to capture it (it seems like it wouldn’t matter in this case but maybe) you can add a lookahead assertion.
(?=...)Assertions make sure that pattern exists, but it doesn’t change what is matched.