Highlight results

Hello,
I would like to say a big thank to Kevin for his book which permit me to realize a web site on an old langage with a search engine based PHP and MySql…
here it is :
http://www.ubaye-verdon.net/barcinonien/formthmr.php
But, now, it would be pleasant if the words found happears differently, i say “stressed” or “thick”…
You see ?
I am not able to do that …!
Can you explain please ?
A new thank for help !

Hi lavercq,

There are several different ways to highlight or apply formatting to script. In most cases it is best to use CSS (Cascading Style Sheets) to define the style that is applied. There are several ways that CSS can be applied:[LIST=1]
[]Outputted using PHP
[
]Use JavaScript
[*]Use a combination of PHP and JavaScript
[/LIST]As you are in the PHP forum the way to do this using PHP is:


$st_styles = null;
$st_styles = "class='st'";
$li_styles = null;
$li_styles = "class='ul_li'";
$ul_styles = null;
$ul_styles = "class='ul';
$list_items = null;
$list_items = array('First:' =>'This is the first item','Second' => 'This is the second item');
$html = null;
$html = "<ul $ul_styles>"
foreach ($list_items as $span_data => $list){
   $html .= "<li $li_styles><span $st_styles>$span_data</span>$list</li>";
}
$html = '</ul>';
echo $html;

In your CSS file that would be linked in the head of your xhtml document you might have:


.st {
  font-weight: 600;
  text-transform: uppercase;
}
.li {
  color: green;
}
.ul {
  padding: 5px;
}

When the PHP outputs and the page loads the CSS file then the formatting defined in the CSS file will apply to the specified HTML elements.

Hope this helps,
Steve

Thank’s for this quick answer.
I will try to understand and apply…
And perhaps…if you accept i will ask a new question…

Hi lavercq,

If you have any questions then I (and others) would be glad to help you understand.

Regards,
Steve

If you want to have an idea of my problem you can look on this page :
http://www.ubaye-verdon.net/provence/formthmH.php
type for example : acqu* in the query box and you will see 19 results for this query

I don’t understand where and how integrate your code in mine…
Here is the lines giving the result :

while ($sql = mysql_fetch_array($resultat))
{
echo("<tr valign=‘top’>
");

$sjhProv = utf8_encode(($sql[‘sjhProv’]));
echo("<td class=‘honorat’>$sjhProv</td>
");

$categorie = (($sql[‘categorie’]));
echo("<td class=‘catg’>$categorie</td>
");

$sjhPhonet = utf8_encode(($sql[‘sjhPhonet’]));
echo("<td class=‘etym’>$sjhPhonet</td>
");

$sjhSynon = utf8_encode(($sql[‘sjhSynon’]));
echo ("<td class=‘oc’>$sjhSynon</td>
");

$sjhLgmed = utf8_encode(($sql[‘sjhLgmed’]));
echo ("<td class=‘med’>$sjhLgmed</td>
");

$sjhFrancais= utf8_encode(($sql[‘sjhFrancais’]));
echo ("<td class=‘fr’>$sjhFrancais</td>
");

$sjhLoc=utf8_encode(($sql[‘sjhLoc’]));
echo ("<td class=‘loc’>$sjhLoc</td>
");

$sjhLocfr=utf8_encode(($sql[‘sjhLocfr’]));
echo ("<td class=‘locfr’>$sjhLocfr</td>
");

$sjhEtym =utf8_encode (($sql[‘sjhEtym’]));
echo ("<td class=‘etym’>$sjhEtym</td>
");

echo("</tr>
");
}
echo(‘</table>’);
?>

I tried this, but less success…:

while ($sqls = mysql_fetch_array($resultat))
{
echo("<tr valign=‘top’>
");
$sql = str_replace($item, ‘<font color=“lime”>’$item’</font>', $sqls);

Why this do not work …?!

Salut lavercq,

Essayez ceci. Vous avez besoin de passer chacune de vos colonnes de base de données, comme $ sql [‘sjhProv’] par le biais de cette classe, puis il mettra en évidence les mots ou parties de mots comme dans l’exemple ci-dessous.

Le rgbhex () méthode pourrait être mis en œuvre comme une couleur fixe, la méthode generated_colours () crée une couleur aléatoire. Mais j’ai emprunté cette méthode à partir d’une autre fonction que je puisse faire la classe plus rapide.

English Version:
Try This. You need to pass each of your database columns, like $sql[‘sjhProv’] through this class and then it will highlight the words or parts of words like in the example below.

The rgbhex() method could be implemented as a fixed colour, the generated_colours() method creates a random colour. But I borrowed this method from another function so I could do the class quicker.


<?php
$text = "- Achat, acquisition faite à prix d'argent";
 
class text_highlight{
    public $output_text;


    function __construct($text, $words){
        $split_words = explode( " " , $words );
        foreach ($split_words as $word){
            $color = self::generate_colors();
            $text = preg_replace("|($word)|Ui" ,
                       "<span style=\\"background:".$color.";\\"><b>$1</b></span>" , $text );
        }
        $this->output_text = $text;
    }
    private function rgbhex($red, $green, $blue){
        return sprintf('#XXX', $red, $green, $blue);
    }
    private function generate_colors(){
        $red = rand( rand(60,100) , rand(200,252) );
        $green = rand( rand(60,100) , rand(200,252) );
        $blue = rand( rand(60,100) , rand(200,252) );


        $color = self::rgbhex( $red , $green , $blue );
        return $color;
    }
}
$highlight = new text_highlight($text , 'acqu');
echo $highlight->output_text;
?>

Steve

C’est très gentil de votre part, mais…je ne sais pas faire le lien avec mon programme !
Je suis surpris par la complexité nécessaire pour un si petit résultat…
Je pensais qu’il suffirait de mettre une ligne comme ceci par exemple :
$sql= str_replace($search, ‘<strong>’.$search.‘</strong>’, $sql);
Vous me parlez classe, je n’ai pas la maîtrise de la programmation objet…
Il faut que je m’y mette, mais comme je veux avancer la copie du dictionnaire (plus de 40.000 mots !) et que je ne suis plus tout jeune !

Bonjour/Hi

J’ai changé l’objet point culminant de sorte qu’il est plus facile pour vous d’utiliser. J’ai aussi donné des exemples à l’aide de votre code. La seule chose que vous avez à faire est de passer les mots de recherche pour la méthode mise en évidence.

I have changed the highlight object so it is easier for you to use. I have also given examples using your code. The only thing you will have to do is to pass the search words to the highlight method.


<?php
 class text_highlight{


    public function highlight($text, $words){
      $split_words = explode( " " , $words );
        foreach ($split_words as $word){
            $color = self::generate_colors();
            $text = preg_replace("|($word)|Ui" ,
                       "<span style=\\"background:".$color.";\\"><b>$1</b></span>" , $text );
        }
        return $text;
    }
    private function rgbhex($red, $green, $blue){
        return sprintf('#XXX', $red, $green, $blue);
    }
    private function generate_colors(){
        $red = rand( rand(60,100) , rand(200,252) );
        $green = rand( rand(60,100) , rand(200,252) );
        $blue = rand( rand(60,100) , rand(200,252) );


        $color = self::rgbhex( $red , $green , $blue );
        return $color;
    }
}


/*
 * Create highlight object:
 * Créer mettre en évidence l'objet:
 */
$o_HT = new text_highlight();
/*
 * Examples of the highlight object's use:
 * Exemples d'utilisation de l'objet point culminant de:
 *
 * $text = "- Achat, acquisition faite à prix d'argent";
 * $words = 'Achat, acu ';
 * echo $o_HT->highlight($text, $words);
 */


/*
 * Here is your code. Using the highlight object.
 * Set the $words variable to the suggest(string) values. 
 * Pass suggest(string) values from JavaScript to PHP
 * 
 * Voici votre code. Utilisation de l'objet en surbrillance.
 * Définissez les mots variable $ aux suggérer (chaîne) des valeurs.
 * Passez suggèrent (chaîne) des valeurs à partir de JavaScript à PHP
 * 
 * You will do the same thing for the variables that need highlighted content
 * 
 * Vous ferez la même chose pour les variables qui ont besoin de contenu mis en évidence
 */
 $sjhFrancais= utf8_encode(($sql['sjhFrancais']));
 $words = /*suggest(string) values*/ /* suggérer (chaîne) des valeurs */
 $sjhFrancais = $o_HT->highlight($sjhFrancais, $words);
 echo ("<td class='fr'>$sjhFrancais</td>\
");


 $sjhLoc=utf8_encode(($sql['sjhLoc']));
 $words =  /* suggérer (chaîne) des valeurs */
 $sjhLoc = $o_HT->highlight($sjhLoc, $words);
 echo ("<td class='loc'>$sjhLoc</td>\
");


 $sjhLocfr=utf8_encode(($sql['sjhLocfr']));
 $words =  /* suggérer (chaîne) des valeurs */
 $sjhLocfr = $o_HT->highlight($sjhLoc, $words);
 echo ("<td class='locfr'>$sjhLocfr</td>\
");
 
 /*
  * When finished with the object close it.
  * Lorsque vous avez terminé avec l'objet le fermer.
  */
 $o_HT = null;
?>

partie la plus difficile
Une variable en JavaScript peuvent être lus directement en PHP. var suggestion =‘’; peut être lu que $ suggestion en PHP. Il s’agit la partie, plus difficile à passer le suggest(string) valorise $o_HT->highlight($text, $words) - $words de paramètre.

A variable in JavaScript can be read directly in PHP. So a JavaScript variable var suggestions =‘’; can be read in php as $suggestions. This will be the most challenging part for you to pass the suggest(string) values the $o_HT->highlight($text, $words) - $words parameter.

Regards
Steve

Vous êtes très aimable de m’écrire en français !
Je vous remercie beaucoup.
J’ai un peu progressé vers la solution, car maintenant les mots trouvés peuvent être mis en relief à la condition qu’ils soient absolument identiques au mot demandé:
ainsi, si l’on met espece ou ESPECE on trouve bien les résultats, mais le mot espèce n’est pas mis en relief !
Si l’on tape troubadour en minuscule on ne trouve rien, mais si l’on ajoute un s, on obtient le résultat en relief.
Si l’on tape TROUBADOUR on ne trouve rien, si l’on ajoute un s, on obtient le résultat, mais sans le soulignement.
Il faut que la demande corresponde exactement au texte dans la base de données.
L’utilisation de l’astérisque * permet de trouver les résultats, mais,là encore, la mise en relief ne se fait pas …
J’ai essayé la fonction ci-dessous, mais ça ne marche pas !
function simple(){
$item = trim($item);
$item = strtolower($item);
$item = strtr($item, “àáâãäåòóôõöøèéêëçìíîïùúûüÿñ”, “aaaaaaooooooeeeeciiiiuuuuyn”);
$item = preg_replace(“[^a-z0-9'-]*”, “”, $item);
return $item;
echo(“$item”);

function item()
{echo(“$item”);}
}

Bonjour/Hi,

Trop aimable, mon français est de la merde.
Too kind, my French is crap.


<?php 
$string = 'attack of the ToMatos';
$keyword = 'to';


if(preg_match('/\\*/',$keyword)){
    // supprimer les fichiers * à partir du mot-clé 
    // remove the * from the keyword
    $keyword = str_replace('*', '', $keyword); 
    // recherche avec joker
    //search with wildcard 
    $string = preg_replace('!('.$keyword.'.*)!i','<span style="color:red">$1</span>',$string); 
} else { 
   // recherche sans joker 
   // search without wildcard
    $string = preg_replace('!('.$keyword.')!i','<span style="color:red">$1</span>',$string); 
}
echo $string;
 ?>

Réglage $keyword = ‘to’
Cette sorties “attaque des ToMatos
Setting $keyword = ‘to’
This outputs “attack of the ToMatos

Si $keyword = ‘to*’, alors cette sortie “attaque des ToMatos
If $keyword = ‘to*’, then this outputs “attack of the ToMatos

Le ‘i’ dans preg_replace(‘!(’.$keyword.‘)!i’ dit pour correspondre à la casse.
The ‘i’ in preg_replace(‘!(’.$keyword.‘)!i’ says to match case insensitivity.

Vous pouvez spécifier un match joker .* comme: preg_replace(‘!(’.$keyword.‘.*)
You can specify a wild card .* match like: preg_replace(’!(‘.$keyword.’.*)

Passez une excellente journée!
Have a great day!

Steve