Jump to content

[SOLVED] Replace specific numbers from a string


giraffemedia

Recommended Posts

What would be the best way to replace multiple numbers from various rows returned from a mysql query?

 

Say I get the following results...

 

2 columns,

1 column,

3 columns,

2 columns,

3 columns,

1 columns...etc etc

 

How can I replace

 

1 with 4.2,

2 with 8.4,

3 with 12.6?

 

Something like the following but obviously I couldn't use three in a row like so...

 

str_replace("1 column", "4.2", $maths);
str_replace("2 columns", "8.4", $maths);
str_replace("3 columns", "12.6", $maths);

 

Anyone have any ideas?

 

thanks

 

James

Link to comment
Share on other sites

Are you always replacing 1 with 4.2, 2 with 8.4, 3 with 12.6?

 

You could do something like:

<?php
$result = '1 columns';
$new_result = str_replace(array('1','2,'3'),array('4.2','8.4','12.6'),$result);
?>

or

<?php
$result = '3 columns';
list($m,$c) = explode(' ',$result);
$m *= 4.2;
$new_result = $m . ' ' . $c;
?>

 

Ken

Link to comment
Share on other sites

that would probably require a preg_replace() due to possibilities of duplicate numbers etc, or repeating patterns such as 33 not wanting to be changed as just 3. if it's a unique result with the exact thing you want changed, you could use str_replace()

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.