Icebergness Posted May 17, 2012 Share Posted May 17, 2012 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 Quote Link to comment Share on other sites More sharing options...
Psycho Posted May 17, 2012 Share Posted May 17, 2012 $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% ) ) Quote Link to comment Share on other sites More sharing options...
silkfire Posted May 17, 2012 Share Posted May 17, 2012 Your regex is malformed. Plus these type of questions we have a specially dedicated Regex forum for. Use this instead: ([\d.]+)% Quote Link to comment Share on other sites More sharing options...
Icebergness Posted May 17, 2012 Author Share Posted May 17, 2012 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! Quote Link to comment Share on other sites More sharing options...
Psycho Posted May 18, 2012 Share Posted May 18, 2012 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.