dittonamed Posted November 10, 2007 Share Posted November 10, 2007 Say I've got this text "0.0113", or "30.6013", or "5.7794" And I want to find the ONE with the 9 in the third place right of the decimal place, (easy enough) THEN... :-\ Replace the 1. third character right of the decimal place with a 1 2. fourth character right of the decimal place with a 7 3. fifth character right of the decimal place with a 5 ... Without changing any other characters Example: $haystack = array(0.0113, 30.6013, 5.7794); foreach ($haystack as $h) { if (preg_match('/\...9/i', $h)) { #Found the right one #Now how to replace only those chars in those positions? ??? } } Anyone out there be such a master?! Y'ahar har Thanks, Ben Quote Link to comment https://forums.phpfreaks.com/topic/76720-regexp-madness/ Share on other sites More sharing options...
Lumio Posted November 10, 2007 Share Posted November 10, 2007 I don't know for what you could need that... but: <?php $haystack = array(0.0113, 30.6013, 5.7794); foreach ($haystack as $i => $h) { if (preg_match('/^([\d]+\.)([\d][\d])(9[\d]*)$/', $h, $match)) { /* the regex means: one or more digit followd by . followed by 2 single digits followed by 9 followed by 0 or more digits and that all should begin from the first sign and ends to the last sign. */ $_h = $match[0]; //get all, that got found if (isset($match[3])) { //if the nine exists - do it! $_tmp = '175'.substr($match[3], 3); $_tmp = substr($_tmp, 0, strlen($match[3])); //remove to many signs... we only want the length we got //so if we only has 94 it won't get 175 but 17 $_h = $match[1].$match[2].$_tmp; } $haystack[$i] = $_h; //put it back into the array } } echo '<pre>'.print_r($haystack,true).'</pre>'; ?> Quote Link to comment https://forums.phpfreaks.com/topic/76720-regexp-madness/#findComment-388536 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.