1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Word Replacer

Discussion in 'PHP' started by adamjblakey, Aug 6, 2014.

  1. #1

    I have a function which i use to replace words in a sentence.

    The issue i am having is it is replacing a section of a word e.g. acknowledge the word know might be replaced with understand so we would be left with acunderstandledge which does not make sense.

    The Mysql tabel is made up like this

    Original work Replacements
    know understand, be aware of
    How do i change the function below so that it only replaces exact full word matches rather than i partial?

    Function below

    function change_text($description){
        $result = mysql_query("SELECT original, replacement FROM `text_replacements`") or die(mysql_error());
        while(list($original, $wordlist) = mysql_fetch_array($result)) {
            // Make an array out of each word list and shuffle it, so we get something new on each run
            $word = explode(', ', $wordlist);
            // Magic happens here
            $tmp = preg_split('/[\s]+/', trim($description));
            $c = count($tmp);
            for($i = 0; $i < $c; $i++){   
                // Remove right whitespace       
                $tmpword = rtrim($tmp[$i]);
                // Save var with original text for replace function later
                $search_text = $tmpword;
                $extra = '';
                // If tmpword starts uppercase, make it lowercase to compare. Replacement will be turned uppercase
                if (ctype_upper(substr($tmpword, 0 , 1))) {
                    $tmpword = strtolower($tmpword);                       
                    $replacement = ucfirst($word[0]);
                else { $replacement = $word[0]; }
                // If word end with .,?! remove from tmpword, so we can use it in the next check
                // create var to append extra signs again
                if(substr($tmpword, -1) == ',' || substr($tmpword, -1) == '.' || substr($tmpword, -1) == '?' || substr($tmpword, -1) == '!') {
                    $extra = substr($tmpword, -1);
                    $tmpword = substr($tmpword, 0, -1);
                // after all checks (lowercase, remove extra chars from tmpword)
                // check if this reduced word is in our replace list
                // If it is replace all
                if(in_array($tmpword, $word)) {
                    $description = str_replace($search_text, $replacement.$extra, $description);
        return nl2br(preg_replace('/([.!?]\s*\w)/e', "strtoupper('$1')", ucfirst(strtolower($description))));
    Code (markup):
    adamjblakey, Aug 6, 2014 IP