• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 370
  • Last Modified:

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.
0
mindwarpltd
Asked:
mindwarpltd
  • 7
  • 7
  • 6
  • +2
3 Solutions
 
Samuel LiewCommented:
<style type="text/css">
span.highlight {
background-color: yellow;
}
</style>
<?
$keyword = "word";
$text = "this sentence contains the word to be highlighted";
$text = preg_replace('/\b'.$keyword.'\b/gi', '<span class="highlight">'.$keyword.'</span>', $text);

echo $text;
?>

Open in new window

0
 
darren-w-Commented:
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);

?>
0
 
mindwarpltdAuthor Commented:
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 !!
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Samuel LiewCommented:
Try this and tell me what you get:
$text = preg_replace($keyword, '<span class="highlight">'.$keyword.'</span>', $text);

Open in new window

0
 
käµfm³d 👽Commented:
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)
0
 
käµfm³d 👽Commented:
Stupid autoreplace on phone. :/

A refectory is "regex". :)
0
 
mindwarpltdAuthor Commented:
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 :(
0
 
darren-w-Commented:
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
0
 
Marco GasiFreelancerCommented:
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.
0
 
mindwarpltdAuthor Commented:
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

0
 
käµfm³d 👽Commented:
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..."
0
 
käµfm³d 👽Commented:
P.S.

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

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

Bye
0
 
mindwarpltdAuthor Commented:
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.
0
 
käµfm³d 👽Commented:
MarqusG's example should suffice. You would just use str_replace instead of preg_replace:

    foreach ($keywords as $k){ $text = str_replace($k, ''.$k.'', $text); }
0
 
käµfm³d 👽Commented:
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.
0
 
käµfm³d 👽Commented:
BTW

That code sample is mangled. Copy/paste didn't seem to want to work that time. :)  adjust the replacement text accordingly.
0
 
Marco GasiFreelancerCommented:
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
0
 
Marco GasiFreelancerCommented:
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

0
 
mindwarpltdAuthor Commented:
Ok got that working :)

However its case sensitive, I'd like yellow highlighted item in their original case ??
0
 
Marco GasiFreelancerCommented:
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
0
 
mindwarpltdAuthor Commented:
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.
0
 
Marco GasiFreelancerCommented:
Oh, I'm sorry: misunderstood the problem. Use code attached to solve this.
You can always use str_replace this way

$text = str_replace($m, '<span class="highlight">'.$m.'</span>', $text);

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

$keywords = array("anti", "virus");

$text = "Anti virus is a must for all";

foreach ($keywords as $k){
    preg_match_all("/$k/i",$text,$matches);
    foreach ($matches[0] as $m){
        $text = preg_replace("/$m/", '<span class="highlight">'.$m.'</span>', $text);
    }
}

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



?>

</html>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 7
  • 7
  • 6
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now