Find a percentage value in a string using preg_match

家住魔仙堡 提交于 2019-12-09 00:03:28

问题


I'm trying to isolate the percentage value in a string of text. This should be pretty easy using preg_match, but because the percentage sign is used as an operator in preg_match I can't find any sample code by searching.

$string = 'I want to get the 10%  out of this string';

What I want to end up with is:

$percentage = '10%';

My guess is that I'll need something like:

$percentage_match = preg_match("/[0-99]%/", $string);

I'm sure there is a very quick answer to this, but the solution is evading me!


回答1:


if (preg_match("/[0-9]+%/", $string, $matches)) {
    $percentage = $matches[0];
    echo $percentage;
}



回答2:


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




回答3:


Why not /\d+%/? Short and sweet.




回答4:


The regex should be /[0-9]?[0-9]%/.

The ranges inside character classes are for 1 character only.




回答5:


$number_of_matches = preg_match("/([0-9]{1,2}|100)%/", $string, $matches);

The match will be in the $matches array, specifically $matches[1].



来源:https://stackoverflow.com/questions/4799671/find-a-percentage-value-in-a-string-using-preg-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!