I am trying to implement this code for my search function which will highlight matched keywords in the result. It is working great but the problem is it won't highlight keywords with special marks like:
$text="iphone mới";
Question 1: If keyword is "mới" it will highlight the word "mới" in $text. But if keyword is "moi", it won't highlight it. By the way, mới = new in my language. So how can i adjust this code to make it work?
Question 2: Also how to make it highlight part of word in $text like: If keyword is "iph" it will also highlight iph of the word iphone in $text.
Many thanks in advance...!!!
<?php
function highlightWords($text, $words)
{
/*** loop of the array of words ***/
foreach ($words as $word)
{
/*** quote the text for regex ***/
$word = preg_quote($word);
/*** highlight the words ***/
$text = preg_replace("/\b($word)\b/i", '<span class="highlight_word">\1</span>', $text);
}
/*** return the text ***/
return $text;
}
/*** example usage ***/
$text = 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
/*** an array of words to highlight ***/
$words = array('php', 'sql');
/*** highlight the words ***/
$highlighttext = highlightWords($string, $words);
?>
<html>
<head>
<title>PHPRO Highlight Search Words</title>
<style type="text/css">
.highlight_word{
background-color: pink;
}
</style>
</head>
<body>
<?php echo $string; ?>
Try this code,
function highlightWords($str, $replaceWord)
{
$new = '<span class="highlight_word">'.$replaceWord.'</span>';
$str = preg_replace_callback( "/$replaceWord/", function( $match) use( $new) {
return $new;
}, $str);
return $str;
}
Related
I have applied this code for my search function. It is currently working great. However, if I typed a keyword without accented letter, it won't highlight the word.
Example:
$text ="iphone mới"
If i typed in keywords "moi", it won't highlight the word "mới" in $text. I also tried u flag in the pattern as suggesttion from google, but it did not work either. Please help...
Here is my code:
<?php
function highlightWords($text, $words)
{
/*** loop of the array of words ***/
foreach ($words as $word)
{
/*** quote the text for regex ***/
$word = preg_quote($word);
/*** highlight the words ***/
$text = preg_replace("/($word)/ui", '<span class="highlight_word">\1</span>', $text);
}
/*** return the text ***/
return $text;
}
/*** example usage ***/
$text = 'this is my iphone mới';
/*** an array of words to highlight ***/
$words = array('moi');
/*** highlight the words ***/
$highlighttext = highlightWords($string, $words);
?>
<html>
<head>
<title>PHPRO Highlight Search Words</title>
<style type="text/css">
.highlight_word{
background-color: pink;
}
</style>
</head>
<body>
<?php echo $highlighttext; ?>
You could use this code:
setlocale(LC_ALL, 'en_US');
$word = iconv("utf-8","ascii//TRANSLIT",$word);
/*** quote the text for regex ***/
This will remove all the diacritics from the $word.
You can then iterate through each character and replace it with a character class (if the character has alternative forms). For example o becomes [ớọơờớòo].
Note: nhahtdh makes a good point. I don't know what language these diacritics come from, much less if any characters should become characters with different diacritics.
If you want to do something along that line, don't flatten the $word and add rules for accented characters, like: ơ becomes [ờớơ].
I want to search engine with LIKE keyword and i want to colored searched word.
My code is:
$result1=mysql_query("SELECT * FROM archives1 where title like '%$search%' || author like '%$search%'") or die (mysql_error());
while($row1=mysql_fetch_array($result1))
{
extract($row1);
echo" <table width='456' height='151' style='table-layout:fixed;'>
<tr><td align='center'>Archives</td></tr>
<tr><td height='38'><b>Section:</b></td><td width='334'>$section</td></tr>
<tr><td height='38'><b>Title:</b></td><td width='334'>$title</td></tr>
<tr><td height='38'><b>Author:</b></td><td width='334'>$author</td></tr>
<tr><td height='38'><b>Country:</b></td><td width='334'>$country</td></tr>
<tr><td height='38'><b>Page Number:</b></td><td width='334'>$pgno</td></tr>";
If i want to search any word with above code then it gives true answer but i want answer with colored text. Only search word should be colored.
How can it be possible?
I have no idea.
use a preg_replace to replace the searched text with a span and add a class to it.
$text = 'sample text';
$query = 'text';
$text = preg_replace('/('.$query.')/','<span class="highlight">$1</span>',$text);
echo $text;
use the highlight class to style the result.
You can use a simple function to highlight arbitrary text:
// Replace string and highlight it
function highlight_words($string, $words, $css_class)
{
//convert searched word to array
$words = array($words);
//cycle
foreach ( $words as $word ) {
$string = str_ireplace($word, '<span class="'.$css_class.'">'.$word.'</span>', $string);
}
/*** return the highlighted string ***/
return $string;
}
Example usage:
$string = 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
$words = array('php', 'sql');
$string = highlightWords($string, $words, 'highlight');
Okay suppose we would like to get title,keywords and description of website so i'm going to use the following function
<?PHP
function getInfo($URL)
{
$getInfo= get_meta_tags($URL);
return $getInfo;
}
$URL = "http://www.my_site.com"; // URL
// Applying the function
$_getInfo = getInfo($URL);
// Print the results.
echo $_getInfo ["keywords"]."<br>"; // gives keywords
echo $_getInfo ["description"]."<br>"; // gives description
?>
Yet,everything if fine but suppose the results as following
Keywords
php,profitable,share
Description
Advanced profitable and featured script to share
As in this example we've some keywords found in description profitable and share
The question is how to highlight keywords that only found in description!!
I will add the following css
<style>
.highlight{background: #CEDAEB;}
.highlight_important{background: #F8DCB8;}
</style>
and will add this function to alter between two different colors just like in css code
<?PHP
function hightlight($str, $keywords = '')
{
$keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
$style = 'highlight';
$style_i = 'highlight_important';
$var = '';
foreach (explode(' ', $keywords) as $keyword) {
$replacement = "<span class='".$style."'>".$keyword."</span>";
$var .= $replacement." ";
$str = str_ireplace($keyword, $replacement, $str);
}
$str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);
return $str;
}
?>
Now applying both (Not working)
$string = hightlight($_getInfo["description"], $_getInfo ["keywords"]);
echo $string;
Why not working cause it define $_getInfo ["keywords"] as one word php,profitable,share
which indeed not found in description in that shape.
so how can i apply it by using explode or foreach (i guess) so the out put be like this :
I wonder if there was another way to do it if mine looks not good way. ~ Thanks
Since your keywords are in list format you need to:
foreach(explode(',', $keywords) as $keyword)
I have a great little script that will search a file and replace a list of words with their matching replacement word. I have also found a way to prevent preg_replace from replacing those words if they appear in anchor tags, img tags, or really any one tag I specify. I would like to create an OR statement to be able to specify multiple tags. To be clear, I would like to prevent preg_replace from replacing words that not only appear in an anchor tag, but any that appear in an anchor,link,embed,object,img, or span tag. I tried using the '|' OR operator at various places in the code with no success.
<?php
$data = 'somefile.html';
$data = file_get_contents($data);
$search = array ("/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(white)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(blue)\b/is");
$replace = array ('Apple','Potato','Boysenberry');
echo preg_replace($search, $replace, $data);?>
print $data;
?>
looking at the first search term which basically says to search for "red" but not inside :
"/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is"
I am trying to figure out how I can somehow add <\/link>,<\/embed>,<\/object>,<\/img> to this search so that preg_replace doesn't replace 'red' in any of those tags either.
Something like this?:
<?php
$file = 'somefile.html';
$data = file_get_contents($file);
print "Before:\n$data\n";
$from_to = array("red"=>"Apple",
"white"=>"Potato",
"blue"=>"Boysenberry");
$tags_to_avoid = array("a", "span", "object", "img", "embed");
$patterns = array();
$replacements = array();
foreach ($from_to as $from=>$to) {
$patterns[] = "/(?!(?:[^<]*>|[^>]+<\/(".implode("|",$tags_to_avoid).")>))\b".preg_quote($f
rom)."\b/is";
$replacements[] = $to;
}
$data = preg_replace($patterns, $replacements, $data);
print "After:\n$data\n";
?>
Result:
Before:
red
<span class="blue">red</span>
blue<div class="blue">white</div>
<div class="blue">red</div>
After:
red
<span class="blue">red</span>
Boysenberry<div class="blue">Potato</div>
<div class="blue">Apple</div>
I am using this class to highlight the search keywords on a piece of text:
class highlight
{
public $output_text;
function __construct($text, $words)
{
$split_words = explode( " " , $words );
foreach ($split_words as $word)
{
$text = preg_replace("|($word)|Ui" ,
"<font style=\"background-color:yellow;\"><b>$1</b></font>" , $text );
}
$this->output_text = $text;
}
}
If
$text = "Khalil, M., Paas, F., Johnson, T.E., Su, Y.K., and Payer, A.F. (2008.) Effects of Instructional Strategies Using Cross Sections on the Recognition of Anatomical Structures in Correlated CT and MR Images. <i>Anatomical Sciences Education, 1(2)</i>, 75-83 "
which already contains HTML tags, and some of my search keywords are
$words = "Effects color"
The first look will highlight the word Effects, with <font style="background-color:yellow">Effect</font>, but the second loop will highlight the word color in the HTML tag. What should I do?
Is it possible to tell preg_replace to only highlight text when its not inside an alligator bracket?
Use a HTML parser to make sure that you only search through text.
You could use a CSS highlighted class instead and then use span tags, eg.
<span class="highlighted">word</span>
Then define your highlighted class in CSS. You could then exclude the word 'highlighted' from being valid in your search. Of course renaming the class to something obscure would help.
This also has the benefit of allowing you to change the highlight colour easily in the future, or indeed allowing the user to toggle it on and off by modifying the CSS.
Why use a loop?
function __construct($text, $words)
{
$split_words = preg_replace("\s+", "|", $words);
$this->output_text = preg_replace("/($split_words)/i" ,
"<font style=\"background-color:yellow; font-weight:bold;\">$1</font>" , $text );
}
A possible work-around would be to first wrap it with characters, which would (to 99%) not be a search input and replace those characters with the html tags after the 'foreach' loop:
class highlight
{
public $output_text;
function __construct($text, $words)
{
$split_words = explode(" ", $words);
foreach ($split_words as $word)
{
$text = preg_replace("|($word)|Ui", "%$1~", $text);
}
$text = str_replace("~", "</b></span>", str_replace("%", "<span style='background-color:yellow;'><b>", $text));
$this->output_text = $text;
}
}