su******@yahoo.co.uk wrote:
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?
Hi
I am unsure how to manage that with preg_replace. Probably it is possible.
But you can easily code it yourself like this:
$temp = "The temperature is 18 Celsius today. Yesterday is was 17 Celsius";
$words = explode(" ",$temp);
// you now have a array with all the words.
// loop through all:
for($i=0;$i<count($words);$i++){
// is it a number?
if (is_numeric($words[$i])){
$fahrenheit = $words[$i] * blabla;
// (I don't know the conversion)
echo " <span class='temp' title='".$fahrenheit." Fahrenheit'>";
echo $words[$i].$words[$i+1]."</span> ";
$i++;
} else {
echo $words[$i]." ";
}
}
Watch the lines:
echo " <span class='temp' title='".$fahrenheit." Fahrenheit'>";
echo $words[$i].$words[$i+1]."</span> ";
$i++;
In there I also include the next word (Celsius), and also must increase the
counter $i by 1 extra. If not done, you will see Celsius 2 times.
But if your sentence end with a number this gives an array out of bound
error.
I didn't check this code, but I guess you will manage from here.
Good luck.
Regards,
Erwin Moller