Jump to content

Database driven tool tips, possibly str_replace?


powelly

Recommended Posts

In the project im currently working on the content of the page is stored in a database in html format, everywhere a word is underlined I need to display a popup onhover and pull the definition of that word from a seperate table.

 

At the moment im looking at using this for the tool tips and have used find and replace to create the tool tips as follows:

 

$content = str_replace("<u>" , "<span class='link'><a href='javascript: void(0)'>" , $content);
$content = str_replace("</u>" , "<span>popup text goes here</span></a></span>" , $content);

 

The issue I now have is how I get the definitions from the table and insert them into the "popup text goes here" bit.

 

Has anyone done anything similar or can you point me in the right direction?

 

Thanks

 

Powelly

 

 

maybe this

 

<?php
$start = "<span class=\'link\'><a href=\'javascript: void(0)\'>";
$end= "<span>popup text goes here</span></a></span>";

$content = "This <u>tests</u> the test!";

$content = preg_replace('%(<u>([^>]*)</u>)%si', "$start\2$end", $content );
?>

Unless ive missed something, you first need to find all the of the words that have been underlined. You then need to search your database for their definitions. Only after doing this can you do the replacement. I would do something like:

 

<?php
$string= 'The <u>text</u> that contains <u>all</u> the underlined links';
preg_match_all('|<u>(.*?)</u>|',$string,$matches);//find all the underlined links
$words = $matches[1];//an array of all the words to look up
$original = $matches[0];//an array of all the original text we will replace later

//sort the array - allows us to select all results from the db in one query - we also order the query by the words so we can match them up
sort($original);

$sql = mysql_query("SELECT `definition` FROM `yourtable` WHERE `word` IN ".implode('\'',$words)." ORDER BY `word`");//select all of the words we want, ordering their definition by the word
$definitions = array();
while($row = mysql_fetch_assoc($sql)){//create an array of all the definitions
$definitions[] = "<span class='link'><a href='javascript: void(0)'>".$row['definition']."<span>popup text goes here</span></a></span>";

}
$string = str_replace($original,$replacement,$string);//do the replacement
?>

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.