Find percentage value in row using preg_match

I am trying to isolate a percentage value in a line of text. This should be pretty easy with preg_match, but since the percent sign is used as the operator in preg_match, I cannot find any sample code by doing a search.

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

In the end, I want:

$percentage = '10%';

I assume that I need something like:

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

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

+3
source share
5 answers
if (preg_match("/[0-9]+%/", $string, $matches)) {
    $percentage = $matches[0];
    echo $percentage;
}
+4
source

use regex /([0-9]{1,2}|100)%/. {1,2}indicates that it matches one or two digits. |says it matches pattern or number 100.

[0-99], 0-9 9, .

. 00, 01, 02, 03... 09. , /([1-9]?[0-9]|100)%/, 1-9

+3

A regular expression should be /[0-9]?[0-9]%/.

Ranges within character classes are for 1 character only.

+1
source

Why not /\d+%/? Briefly and clearly.

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

The match will be in the array $matchesin particular $matches[1].

0
source

Source: https://habr.com/ru/post/1787828/


All Articles