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 Link to comment https://forums.phpfreaks.com/topic/262678-finding-percentage-in-string/ 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% ) ) Link to comment https://forums.phpfreaks.com/topic/262678-finding-percentage-in-string/#findComment-1346356 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.]+)% Link to comment https://forums.phpfreaks.com/topic/262678-finding-percentage-in-string/#findComment-1346360 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! Link to comment https://forums.phpfreaks.com/topic/262678-finding-percentage-in-string/#findComment-1346373 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. Link to comment https://forums.phpfreaks.com/topic/262678-finding-percentage-in-string/#findComment-1346533 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.