String replace help

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I have some strings like this: "The temperature is 18 Celsius today".
Some strings may have more than one value in them, like "The
temperature is 18 Celsius today. Yesterday is was 17 Celsius".

I want to display these, adding a tooltip when the mouse pointer is
over the "18C section, such that it shows the value in Fahrenheit
instead of Celsius. Something like this:

The temperature is <span class="temp" title="64 Fahrenheit">18
Celsius</span> today.

I need some way to do a string replace to add the <span>, but with a
calculation to work out the new value. Can preg_replace do something
like this?

Re: String replace help


Quoted text here. Click to load it

Yep, with the modifier /e which interprets the replacement string as PHP

function C2F($temp) {
  return ($temp + 32) * 1.8;

$pattern = '#((\d+)\s*celsius)#ei';
$replace = 'sprintf("<span class=\"temp\" title=\"%.1fF\">$1</span>", C2F($2))';
$text = preg_replace($pattern, $replace, $text);

If you want a longer title, use this instead:

$replace = 'sprintf("<span class=\"temp\" title=\"%.1f Fahrenheit\">$1</span>",


Site Timeline