Jump to content

Regexp madness...


dittonamed

Recommended Posts

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)  :D

 

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

Link to comment
Share on other sites

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>';
?>

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.