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

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

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()

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.