Solved

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

Posted on 2010-09-12
24
336 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
  • 7
  • 7
  • 6
  • +2
24 Comments
 
LVL 14

Assisted Solution

by:sam2912
sam2912 earned 50 total points
Comment Utility
<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-
Comment Utility
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
Comment Utility
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
 
LVL 14

Expert Comment

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

Open in new window

0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
Stupid autoreplace on phone. :/

A refectory is "regex". :)
0
 

Author Comment

by:mindwarpltd
Comment Utility
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-
Comment Utility
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 30

Expert Comment

by:Marco Gasi
Comment Utility
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
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
P.S.

Performance of a plain string replace will always beat a regex.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:mindwarpltd
Comment Utility
Kaufmed, ok so how do I use string replace with more than one word to do this.
0
 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
To create array do this

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

Bye
0
 

Author Comment

by:mindwarpltd
Comment Utility
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 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 50 total points
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
BTW

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

Expert Comment

by:Marco Gasi
Comment Utility
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 30

Expert Comment

by:Marco Gasi
Comment Utility
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
Comment Utility
Ok got that working :)

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

Expert Comment

by:Marco Gasi
Comment Utility
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
Comment Utility
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 30

Accepted Solution

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
jquery, html5 UI 1 47
Urgent need help ASAP With CSS 5 20
mysql left join sentence 7 19
bootstrap table auto width input box 1 19
This article discusses how to create an extensible mechanism for linked drop downs.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
In this tutorial viewers will learn how to style different bullet points for unordered lists in CSS. Begin with a normal unordered list; the default bullet point is a solid circle: In the CSS, create a defined class of unordered list by typing "ul.S…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

744 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now