Link to home
Create AccountLog in
Avatar of mindwarpltd
mindwarpltd

asked on

Whats the code to regex with php to replace a keyword with a yellow highlight

I need a regex and php code to replace a keywords and replace with html which will show a yellow highlight. This is for a search page. Im guessing I'll need some css for the yellow highlight, I need that too.
SOLUTION
Avatar of Samuel Liew
Samuel Liew
Flag of Australia image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
You would look at the function preg_replace (http://www.php.net/manual/en/function.preg-replace.php)

The regex you need will dependant on what text you want to find

The syntax will look something like this;

<style>
.yellow{
background-color:yellow;
}
</style>
<?php

$tofind="[regex]"; // you need your regex here
$replace_text = "the text";
$to_replace_with="<span class='yellow'>$replace_text</span>";
preg_replace($tofind,$to_replace_with,$to_search);

?>
Avatar of mindwarpltd
mindwarpltd

ASKER

sam2912, this looks promising, but I copied and pasted your code and go nothing echo'd out, but the rest of the php on my page was fine.

I added

echo "#" . $text . "#";

And got

##

darren-w-, I did say I need the regex too !!
Try this and tell me what you get:
$text = preg_replace($keyword, '<span class="highlight">'.$keyword.'</span>', $text);

Open in new window

Avatar of kaufmed
It's hard to give you a refectory when you haven't really defined what you're looking for. If you're just looking to replace a series of keywords, then You can just list the keywords using a pipe as a separator. A pipe regex means "or". Example:

    preg_replace("/fun|games|serious things/", $data, $styleinfo)
Stupid autoreplace on phone. :/

A refectory is "regex". :)
sam2912, same.

kaufmed, The search string would be some text like "the word I am looking for is a word, ok!"

So I'd want the code to replace word each time with a highlighted yellow word.

Its a search script so the word or phrase would be different each time.

Oh this makes things more complicated I guess if they search for more than one word I'd need those highlighted too and they may not be next to each other :(
Perhaps using str_replace() would be better, you could pass the strings you are looking to replace as an array?, and ypu dont need a regex
How you grab page results? I mean: have you put all search results in a single string so we can apply reg exp to that string? If so sam2912 solution should work with some adjustements due to your last  post.

Supposing your string with search result be $text do this:

First, put your keiwords in an array $keywords. Then iterate in array applying sam solution

foreach ($keywords as $k){
  $text = preg_replace(/"$k/", '<span class="highlight">'.$k.'</span>', $text);
}

In css file put this

.highlight{
  background:yellow;
}

This should work fine.
MarqusG, Not sure whats wrong, but the code doesn't work, not sure if its your code or something I have.
<html>
<style type="text/css">
span.highlight {
background-color: yellow;
}
</style>
<?php

$keywords = "word the";

$text = "this sentence contains the word to be highlighted";

foreach ($keywords as $k){
  $text = preg_replace(/"$k/", '<span class="highlight">'.$k.'</span>', $text);
}


echo "#" . $text . "#";



?>

</html>

Open in new window

I'm inclined to agree with darren-w-. Regex is all about matching patterns--not necessarily words. For your purposes, I thing str_replace will fit your needs. Regex would be more for some thing like, "I want to replce all words which start with..."
P.S.

Performance of a plain string replace will always beat a regex.
Kaufmed, ok so how do I use string replace with more than one word to do this.
To create array do this

$keywords = array("word", "the");

Bye
marqusG, but I'll have a string something like this "accountancy software", I'll need that to work with string replace function. They won't be separate variables.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Don't think of the replacements as working on words...  rather they work on substrings. A substring is a string that is contained within another string. The fact that you have multiple words in your search terms is of no issue because you will be searching for that particular string within your target data.
BTW

That code sample is mangled. Copy/paste didn't seem to want to work that time. :)  adjust the replacement text accordingly.
Yes, you have a string that you get from a text input: Probably you have something like

$mykeyords = $_POST['keywords''];

Whatever be keywords, to seacrh for them implies you convert the single string you get from $_POST to an array having for each keyword a distinct element. So you'll do

$keywords = explode(" ", $_POST['keuwords'];

if you have a space as separator. Otherwise, you'll replace space with your actual separator.

Then you can iterate into array using preg_replace or str_replace.

Bye
The below snippets works fine both with preg_replace and str_replace: comment/uncomment as you wish.

Bye
<html>
<style type="text/css">
span.highlight {
background-color: yellow;
}
</style>
<?php

$keywords = array("word", "the");

$text = "this sentence contains the word to be highlighted";

foreach ($keywords as $k){
//  $text = preg_replace("/$k/", '<span class="highlight">'.$k.'</span>', $text);
  $text = str_replace($k, '<span class="highlight">'.$k.'</span>', $text);
}


echo "#" . $text . "#";



?>

</html>

Open in new window

Ok got that working :)

However its case sensitive, I'd like yellow highlighted item in their original case ??
str_replace is case-sensitive
str-ireplace is case-insensitive

If you want to use preg_replace, the provided version is case-sensitive. For case-insensitive replacements use
the modificatore /i

$text = preg_replace("/$k/i", '<span class="highlight">'.$k.'</span>', $text);

Bye
Yeah but as I say, lets say I'm searching on "anti virus"

The search string would be "Anti virus is a must for all"

Both of these would make the A in Anti lower case.
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.