Jump to content

Highlight a word using PHP


toolman

Recommended Posts

It was my mistake - I meant to highlight a word that is already in the page. For example, highlight the word "hello" in a sentence

"hello my name is bob" And also each other time the word "hello" appears.

 

Already on the page?  I'm not following, could you provide an example.  The example given does highlight each occurrence of the desired word.

Link to comment
Share on other sites

Thanks, that has removed the error, but I cannot see the code working.

 

This is what I have tried:

 

<?php

$word = 'and';

$sentence = 'hello world';

$sentence = str_replace($word,'<span style="background-color:#ffff00;">'.$word.'</span>',$sentence);

echo $sentence;

?>

 

<p>and this is a test</p>

 

[/p]

 

the word "and" is not highlighted.

Link to comment
Share on other sites

In my case I have multiple words and characters like + and - as the word because they are search terms like +funny + video, or can be funny video or even just a single word.

 

I made a function to handle and explode the words so can highlight them all if using multiple words or still does the single words too.

 

I'm in the process of making different colors for when there are multiple words.

 

<?php
function highlighter($words, $content) {
    preg_match_all('~\w+~', $words, $matched);
    if(!$matched) {
        return $content;
        }
$regex_pattern = '~\\b('.implode('|', $matched[0]).')\\b~i';

    return preg_replace($regex_pattern, "<span style='background-color:#43C6DB;'><FONT COLOR=Yellow>$0</FONT></span>", $content);
}
?>
<?php
//some sample content and words
$the_single_word = "single";
$the_words = "The words";
$content = "This is the content area or any text area values you want. It should highlight any time the words or The Words or even the Words are used. It will highligt any time the or any time words is used. The Words is the multiple version, if want just a single word then use just one word. I'll use an example word like singleton. See, has to match the word. Stuff like +single , are you single?, or single.com works.<br />";

//example usage
$content_area =highlighter($the_words,$content);
$content_area_2 =highlighter($the_single_word,$content);

//show results
echo "<h2>Multiple words</h2>";
echo "$content_area<br />";

echo "<h2>Single words</h2>";
echo "$content_area_2";
?>

 

Live Demo

http://get.blogdns.com/highlight-words.php

Link to comment
Share on other sites

I completed the multi-word multi-color text highlighter.

 

You can see a demo of the code here.

http://dynaindex.com/color-highlighter.php

 

Or can see it in use with my random url/search

http://dynaindex.com/random-url.php

The random works better with the filter set to off.

 

Here's the code function

<?php
function highlighter($words, $content, $backgroundcolors=null, $fontcolors=null) {
if ($words == '' || $words == null) {
return $content;
exit;
}
        if(is_null($backgroundcolors) || !is_array($backgroundcolors)) {
                $backgroundcolors = array('yellow', 'red', 'green', 'orange', 'aqua', 'lightskyblue ', 'pink', 'lime', 'fuchsia', 'maroon', 'navy', 'olive', 'purple', 'gray', 'silver', 'teal', 'grey');                
                if(is_null($fontcolors) || !is_array($fontcolors)) {
                $fontcolors = array('black', 'white', 'lime', 'oldlace');//change font colors or add more
                }
        }
        $counting = 0;
        $numbercolors = max(array_keys($backgroundcolors));
        foreach ($words as $word) {
            $word = preg_quote(str_replace(array('+','-'), '',trim($word)));            
$content = preg_replace("/\b($word)\b/i", '<span style="background-color:'.$backgroundcolors[$counting].';font-family:arial;color:'.$fontcolors[$counting].';">\1</span>', $content);
                if($counting==$numbercolors){ $counting = 0; } else { $counting++; }
        }     
        return $content;
}
?>

 

Here's the usage

<?php
//example text
$text_or_variable = "This is an example of a multi-color multi-word text highlighter. Is most useful for search words, but can be used also for categories, tags, or any word as well. I integrated the css style into output, is no need to add stylesheet or add code anywhere else. Because this is tailored for search results, I eliminated the + or - in the highlighter results, will just show the word.<br /> Let's try some example using just test to see the results:<br /> ?test test? test.com http://test.com mytest.com test@test.com test-testing<br /> The highlight colors follow the order and pattern of the word versus position colors in the arrays";
//example words
$word_or_words = array('test','multi', 'search', 'code', 'operator', 'classic', 'word', 'show', 'try');

//this is the code to use the function, replace $word_or_words, $text_or_variable with your variables
echo "<h1>Auto Colors</h1>";
$auto_colors =  highlighter($word_or_words, $text_or_variable);//auto colors

echo $auto_colors;


echo "<h1>Defined Colors</h1>";
$defined_colors =  highlighter($word_or_words, $text_or_variable, $backgroundcolors=array('gold','red','yellow', 'pink'), $fontcolors=array('fuchsia','greenyellow','black','white','lime'));//defined colors in arrays

echo $defined_colors;
?>

Link to comment
Share on other sites

And here is a slightly different version of function if need to explode from and make specific arrays.

 

function highlighter($words, $content, $backgroundcolors=null, $fontcolors=null)
{
preg_match_all('~\w+~', $words, $matched);
    if(!$matched) {
        return $content;
       }
$words = str_replace(array('+','-'), "", $words); 
$words = str_replace(" ", "|", $words);
$words = trim($words);
$words = explode("|", $words);
        if(is_null($backgroundcolors) || !is_array($backgroundcolors)) {
                $backgroundcolors = array('yellow', 'red', 'green', 'orange', 'aqua', 'lightskyblue ', 'pink', 'lime', 'fuchsia', 'maroon', 'navy', 'olive', 'purple', 'gray', 'silver', 'teal', 'grey');
                if(is_null($fontcolors) || !is_array($fontcolors)) {
                $fontcolors = array('black', 'white', 'lime', 'oldlace');//change font colors or add more
                }
        }
        $counting = 0;
        $numbercolors = max(array_keys($backgroundcolors));
        foreach ($words as $word) {
            $word = preg_quote(trim($word));               
$content = preg_replace("/\b($word)\b/i", '<span style="background-color:'.$backgroundcolors[$counting].';font-family:arial;color:'.$fontcolors[$counting].';">\1</span>', $content);
                if($counting==$numbercolors){ $counting = 0; } else { $counting++; }
        }
        
        return $content;
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.