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

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.