Replace words within a variable from database

PythonPython Forum LeaderThe Royal RAM
Ok lets say for example weve got the following:

[PHP]$variable = "You are visiting Dev Dreams";[/PHP]

Then in a database there is a table which has got a list of words which each has its own unique id... If for example one of the words was 'Dreams' in the database I would want to replace the words 'Dreams' in the variable with a link to word.php?id=X where X is the words id.

So basically it will replace the words which are in the database with a link....

How can this be done? I know a way of doing it I think but dont think its the best.

Thanks

The Royal Ram

Comments

  • ChroderChroder Senior Member The Royal RAM
    It'd be easiest to just query the database and get all of the words. Then just loop through and str_replace.

    [php]$res = mysql_query("SELECT * FROM words");

    while($data= mysql_fetch_array($res))
    {
    $link = "<a href=\"word.php?id={$data}\">{$data}</a>";
    $variable = str_replace($data, $link, $variable);
    }[/php]

    If you have a lot of words, doing this on every pageload will not be very efficient. So it would be wise to save the output.
  • PythonPython Forum Leader The Royal RAM
    ahh I see. Ok thanks for that.

    What exactly do you mean by 'save the output'. Do you mean some sort of cache? The reason I ask is simply because after a while there probably would be quite a lot of words.

    The Royal Ram

  • ChroderChroder Senior Member The Royal RAM
    Yeah, a cache.

    So if you have this data in a database, it would be useful to add another column like "content_parsed" that would save any text modifications you did. This would save you an extra query per page load (queries are a big time waster), and save you from running through and executing a find-and-replace.

    For example, vBulletin caches parsed posts. It converts the post bbcodes to plain HTML, stores a cache, and just retrieves that instead of re-parsing all the time.
  • PythonPython Forum Leader The Royal RAM
    I see :)

    Also what about lower and upper case. Ive got it working fine but it obviously only replaces it if the word is the exact same case as what it is in the database. How do I do it so it would replace no matter what the case it.

    The Royal Ram

  • ChroderChroder Senior Member The Royal RAM
    Use str_ireplace(), which is the case-insensitive version of str_replace().
  • PythonPython Forum Leader The Royal RAM
    Ok thanks for that

    The Royal Ram

Sign In or Register to comment.