itajackass
itajackass

Reputation: 488

Extract percentage from a string in PHP

I'd like to extract percentages from a string in php but I got a problem if number has not decimal.

Actually, I use this:

$string = "This is a text with value 10.1%"

preg_match("/[0-9]+\.[0-9]+%/", $string, $matches);

In this example all works great cause I can extract: 10.1%

But with this string:

$string = "This is a text with value 10%"

...nothing returned.

I'd like to extract 10% or 10.1% (with decimals) with same code. Any help will be appreciated.

Upvotes: 1

Views: 428

Answers (2)

PHP Hupp Technologies
PHP Hupp Technologies

Reputation: 1952

Try to include . in regex:

$string = 'I want to get the 10.1%  out of this string';
if (preg_match("/[0-9].+%/", $string, $matches)) {
    $percentage = $matches[0];
    echo $percentage;
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521997

Try matching \d+(?:\.\d+)?%, which makes the decimal component of the percentage optional:

$string = "This is a text with decimal value 10.1% and non decimal value 5%.";
preg_match_all("/\d+(?:\.\d+)?%/", $string, $matches);
print_r($matches[0]);

This prints:

Array
(
    [0] => 10.1%
    [1] => 5%
)

Upvotes: 1

Related Questions