Find a percentage value in a string using preg_match
if (preg_match("/[0-9]+%/", $string, $matches)) {
$percentage = $matches[0];
echo $percentage;
}
use the regex /([0-9]{1,2}|100)%/
. The {1,2}
specifies to match one or two digits. The |
says to match the pattern or the number 100.
[0-99]
which you had matches one character in the range 0-9
or the single digit 9
which is already in your range.
Note: This allows 00, 01, 02, 03...09 to be valid. If you do not want this, use /([1-9]?[0-9]|100)%/
which forces one digit and an optional second in the range 1-9
Why not /\d+%/
? Short and sweet.