Jump to content

Finding percentage in string


Icebergness

Recommended Posts

Hi,

 

I'm trying to extract a percentage from data sent through a form. In the below example, I'm trying to dig out the "5%" part, however, this can often be multiple digits, sometimes including decimals as well. Basically I need the numbers and decimals preceding the % symbol, so "5%", "123.456%" and so on.

 

<?php

$text = "Bob the builder 5% 17/05/12";

$n = preg_match_all('/ (.*?)%/s', $text, $match); 
if ($n)
	{ 
    			$search=$match[0]; 
    			for ($k=0;$k<$n;$k++)
    				{ 
            				$accpay = $search[$k];
    				} 
	}

?>

 

This example gives me the result "the builder 5%". Does anyone know how I can further restrict this? It works fine if 5% is at the start of the string, but the string can be given in any order unfortunately.

 

Cheers

Link to comment
https://forums.phpfreaks.com/topic/262678-finding-percentage-in-string/
Share on other sites

$text = "Bob the builder 5% 17/05/12 and 33.456% on another day, but fdsfd% is not valid";
preg_match_all('#[\d|.]+%#', $text, $matches);
print_r($matches);

 

Output

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

Your regex is malformed. Plus these type of questions we have a specially dedicated Regex forum for.

 

Use this instead:

 

([\d.]+)%

 

Sorry :( now that you've pointed the sub-forum out, I feel an idiot for missing it

 

 

$text = "Bob the builder 5% 17/05/12 and 33.456% on another day, but fdsfd% is not valid";
preg_match_all('#[\d|.]+%#', $text, $matches);
print_r($matches);

 

Output

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

 

Thank you for your help :) this was exactly what I was looking for!

Actually, silkfire's solution was closer to what you needed. I mistakenly used the pipe "|" in the character class to signify an OR condition. But, that was incorrect in that context. You should use

preg_match_all('#[\d.]+%#', $text, $matches);

 

. . . although the chances of having the pipe symbol next to a percentage would be very rare.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.