Home > Software engineering >  Extract percentage from a string in PHP
Extract percentage from a string in PHP

Time:12-09

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.

CodePudding user response:

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%
)

CodePudding user response:

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;
}
  •  Tags:  
  • php
  • Related