Solved

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

Posted on 2010-09-12
24
348 Views
Last Modified: 2012-05-10
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
Comment
Question by:mindwarpltd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 7
  • 6
  • +2
24 Comments
 
LVL 14

Assisted Solution

by:sam2912
sam2912 earned 50 total points
ID: 33656598
<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
 
LVL 13

Expert Comment

by:darren-w-
ID: 33656627
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
 

Author Comment

by:mindwarpltd
ID: 33656666
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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 14

Expert Comment

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

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33656704
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33656707
Stupid autoreplace on phone. :/

A refectory is "regex". :)
0
 

Author Comment

by:mindwarpltd
ID: 33656729
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
 
LVL 13

Expert Comment

by:darren-w-
ID: 33656755
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
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 33656768
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
 

Author Comment

by:mindwarpltd
ID: 33656794
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33656795
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33656800
P.S.

Performance of a plain string replace will always beat a regex.
0
 

Author Comment

by:mindwarpltd
ID: 33656808
Kaufmed, ok so how do I use string replace with more than one word to do this.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 33656814
To create array do this

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

Bye
0
 

Author Comment

by:mindwarpltd
ID: 33656829
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
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 50 total points
ID: 33656833
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33656845
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33656861
BTW

That code sample is mangled. Copy/paste didn't seem to want to work that time. :)  adjust the replacement text accordingly.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 33656881
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
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 33656894
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
 

Author Comment

by:mindwarpltd
ID: 33657021
Ok got that working :)

However its case sensitive, I'd like yellow highlighted item in their original case ??
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 33657037
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
 

Author Comment

by:mindwarpltd
ID: 33657058
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
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 400 total points
ID: 33657107
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

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
This article discusses four methods for overlaying images in a container on a web page
In this tutorial viewers will learn how to customize the background color and font color of highlighted text using the ::selection element in CSS Begin by defining the selected text as an element in CSS by typing "::selection": Style the ::selection…
In this tutorial viewers will learn how to embed custom externally-hosted Google Fonts using the Google Font API in CSS Go to the Google Fonts website at google.com/fonts: Browse or search based on font properties or name to find a suitable font for…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question