Jump to content

my basic search color keywords !!


yami007

Recommended Posts

this is my simple code

<?php   
   $search = "new day has come a";
   //$search = "a";
   
   $keywords = preg_split("/[\s,]+/", "$search");
   
   $patterns = array();
   $replacements = array();
   
   foreach( $keywords as $key ) {
      
      $patterns[] = "/$key/";
   }
   
   foreach( $keywords as $key ) {
      
      $replacements[] = "<b>$key</b>";
   }
   
   echo preg_replace($patterns, $replacements, 'a new day has come');
?>

 

the result is : a new day has come

why does a takes over the others ??

Link to comment
https://forums.phpfreaks.com/topic/188048-my-basic-search-color-keywords/
Share on other sites

It goes through the array in order, and as it matched a before day it changed it to d<b>a</b>y. The simplest thing you can do is this

<?php

$search = "new day has come a";
//$search = "a";

$keywords = preg_split("/[\s,]+/", "$search");

$patterns = array();
$replacements = array();

foreach ($keywords as $key) {

$patterns[] = '/\b'.preg_quote($key).'\b/i';
$replacements[] = "<b>$key</b>";
}

echo preg_replace($patterns, $replacements, 'a new day has come');

?>

If you use my code above you will see that it matches all of them. This is done by adding the \b to either side of the regex (which is the boundary shorthand) and this means it will not match mid word, only full words

sorry i misunderstood :s*

thank you : )

It's to highlight all the words in a text with the search terms. The text would obviously be longer than the test text

yeah well, excuse me to ask again, assume the text is : " if today was your last day "

i dont want to highlight a everywhere but i want to highlight day

i wonder how i can do this !!!

It's to highlight all the words in a text with the search terms. The text would obviously be longer than the test text

Ahh I see the replace is being ran on a separate input.

 

It's to highlight all the words in a text with the search terms. The text would obviously be longer than the test text

yeah well, excuse me to ask again, assume the text is : " if today was your last day "

i dont want to highlight a everywhere but i want to highlight day

i wonder how i can do this !!!

Since JAY6390's pattern matches \b$word\b it will not replace an a unless it is just an a. \b matches word boundaries.

Archived

This topic is now archived and is closed to further replies.

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