I have a PHP script that pulls keywords from a MySQL database and I need help with figuring out how to link each word.
An example MySQL entry:
cow moo white black
Need to output in link form:
<a href=word.php?word=cow>cow</a> <a href=word.php?word=moo>moo</a>, etc.
Thank you
Try this:
$output = "";
$mysql_str = "cow moo white black";
$keywords = explode(" ", $mysql_str);
foreach ($keywords as $keyword) {
$output .= "".$keyword." ";
}
echo $output;
If $row["entry"] is the entry, then as follows:
$fieldArray = split(" ", $row["entry"]);
foreach($fieldArray as $item) {
echo "" . $item . "";
}
Related
I tried most of solution answered here but all of them have same problem which is my question here.
I use this function for highligh search results:
function highlightWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
return str_replace($words, $highlighted, $searchtext);
}
Problem occurs when i search text with 2 or more strings separated with spaces and any of them have any of HTML code from my highlighted array.
For example, searchtext="I have max system performance" AND searchstrings="max f"
In first iteration foreach will replace every max with <font color='#00f'><b>max</b></font>
In second iteration it will replace every f with <font color='#00f'><b>f</b></font>
Second iteration will also replace html tags inserted in first replacement!
So it will replace f in string <font color='#00f'> also?
Any suggestion?
Thanks
Miodrag
<?php
$searchtext = "I have max system performance";
$searchstrings = "max f";
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
echo strtr($searchtext, array_combine($words, $highlighted));
?>
Maybe this is good Solution for you?
function highlightWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = '<span class="highlighted-word">'.$word.'</span>';
}
return str_replace($words, $highlighted, $searchtext);
}
echo highlightWords('I have max system performance', 'max f');
?>
You need to add a little bit CSS on your Page:
<style>
.highlighted-word {
font-weight: bold;
}
</style>
Outputs:
I have max system performance
---
UPDATE:
If you like to hightlight the complete word, look at this:
function highlightCompleteWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$searchtext = preg_replace("/\w*?".preg_quote($word)."\w*/i", "<span class='highlighted-word'>$0</span>", $searchtext);
}
return $searchtext;
}
echo highlightCompleteWords('I have max system performance', 'max f');
Outputs: I have max system performance
I might not fully understand your question, but I guess you want to highlight every matched word in the search string.
You could probably just do something like:
$returnString = $searchtext;
foreach ( $words as $word ){
$returnString = preg_replace('/\b'.$word.'\b/i', "<font color='#00f'><b>$0</b></font>", $returnString);
}
return $returnString;
This would output: "I have max system performance"
Since the "f" wouldn't get matched
EDIT - This is if you wanna match part of a word as well.
Kind of ugly but I believe this will fork for you
$returnString = $searchtext;
foreach ( $words as $word ){
if(strlen($word)>2){
$returnString = preg_replace('/'.$word.'/i', "§§§$0###", $returnString);
}
}
$returnString = preg_replace("/\§§§/","<font color='#00f'><b>", $returnString);
$returnString = preg_replace("/\###/","</b></font>", $returnString);
return $returnString;
Try the following
foreach ( $words as $word ){
if(strlen ($word)>2)
{
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
}
I want to display the student names from db and two buttons for each students.
In my code i am using ajax function.
controller
function get_sib_filter()
{
$list_id= $this->input->post('id2');
if(($list_id)==1)
{
$filtered_students = $this->home_model->filter_by_sibling();
$new_string = "";
foreach($filtered_students->result() as $detail)
{
$new_string.=$detail->applicant_first_name;
$new_string=$new_string.'Selected For Interview';
$new_string=$new_string.'Rejected</br>';
}
echo $new_string;
}
}
But i got the last name only(last name and two buttons)
I want list all name and all name having two buttons
Plzz give suggetions..
Like mentioned in the comments above, here are the issues found:
you never defined $new_string
you are overwriting $new_string
you are not concatenating the base_url the right way
Also, since you are using base_url you should be loading the URL helper in your controller ($this->load->helper('url')) or autoloading it in autoload.php
Try this:
$students = $filtered_students->result();
$string = "";
foreach ($students as $student) {
$string .= $student->applicant_first_name . " ";;
$string .= "<a href='" . base_url() . "home/change_filter_status_green/$student->applicant_id' class='btn green button_style' title='Filter'>Selected For Interview</a> | ";
$string .= "<a href='" . base_url() . "home/change_filter_status_red/$student->applicant_id'' class='btn red but_style' title='Rejected'>Rejected</a><br/>";
}
echo $string;
You are overwriting the string here. Please make some changes as shown below.
$new_string = ""; // Define $new_string..
foreach($filtered_students->result() as $detail){
$new_string.=$detail->applicant_first_name;
$new_string.='Selected For Interview';
$new_string.='Rejected<br />';
}
And also make sure what are you getting from this variable: $filtered_students.
You can check it by print_r($filtered_students);
Try the following code:
function get_sib_filter()
{
$list_id= $this->input->post('id2');
if($list_id == 1)
{
$filtered_students = $this->home_model->filter_by_sibling();
$new_string = "";
$count = 0;
foreach($filtered_students->result() as $detail)
{
if($count == 0){
$new_string = "<a href='".base_url('home/change_filter_status_green/').$detail->applicant_id."' class='btn green button_style' title='Filter'>Selected For Interview</a><a href='".base_url('home/change_filter_status_red').$detail->applicant_id."' class='btn red but_style title='Rejected'>Rejected</a>";
$count++;
}else{
$new_string .= $new_string."<a href='".base_url('home/change_filter_status_green/').$detail->applicant_id."' class='btn green button_style' title='Filter'>Selected For Interview</a><a href='".base_url('home/change_filter_status_red').$detail->applicant_id."' class='btn red but_style title='Rejected'>Rejected</a>";
}
}
echo $new_string;
}
}
change your model like this:
function filter_by_sibling()
{
$this->db->select('applicant_id,applicant_first_name');
$this->db->from('student_application');
$this->db->order_by('sib_count','desc');
$result = $this->db->get()->result_array();
return $result;
}
Modify your controller function like this:
function get_sib_filter()
{
$list_id= $this->input->post('id2');
if(($list_id)==1)
{
$filtered_students = $this->home_model->filter_by_sibling();
$new_string = "";
foreach($filtered_students as $detail)
{
$new_string .=$detail['applicant_first_name'];
$new_string .='Selected For Interview';
$new_string .='Rejected<br />';
}
echo $new_string;
}
}
I have a string and some words, i want to highlight those words which match with string, and also i want to print only those words which are highlighted, like if apple matches, then only apple must be printed.
$string = "apple computer";
$keyword = "apple,orange,bike";
I am using the following function to highlight specific characters in a string.
$str = preg_replace("/($keyword)/i","<span style='color:orange;'>$0</span>",$string);
The problem is I want to show only those characters which are highlighted, currently it shows all the characters.
This would meet your need.
$string = " apple computer orange";
$keywords = "apple, orange";
$exp_kwd = explode(",", $keywords);
$res = "<span style='color:orange;'>";
foreach($exp_kwd as $val){
if(strpos($string, trim($val))){
$res .= $val." ";
}
}
$res = $res."</span>";
echo $res;
Hopefully this also will work
$string = "apple computer orange tested";
$keyword = "apple,orange,bike,tested";
$pattern="/".str_replace(",","/,/",$keyword)."/";
$pattern=explode(",",$pattern);
$string=explode(" ",$string);
$keyword =explode(",",$keyword);
$string=implode(",",(preg_filter($pattern, $keyword, $string)));
echo $string="<span style='color:orange;'>$string</span>";
$string = "Im On #Here";
$keyword = "#";
$var = strrchr($string,$keyword);
if(empty($var))
{
echo 'No Occerunce Found';
}
else
{
echo '<span style="color:orange;">'.$var.'</span>';
}
phpfiddle Preview
I need some help. I have a section that displays keywords "tags":
<?=str_replace(",",",",$line["m_tags"])?>
The code above looks like this
Tags: KEYWORD1, KEYWORD2, KEYWORD3
All I'm trying to do is have each individual KEYWORD be a hyperlink to link back to the main page.
Any help would be appreciated.
The code you posted does nothing, it replaces , with ,.
You can do this with regular expressions, but here is a different method:
$output = '';
$tmp = explode(",",$line['m_tags']); /* convert to array */
foreach($tmp as $tag)
$output .= ''.$tag.', '; /* put link in output */
echo substr($output,0,-2); /* echo output without the last , */
Shorter alternative as Felix Kling pointed out:
$tmp = explode(",",$line['m_tags']); /* convert to array */
foreach($tmp as $key => $tag)
$tmp[$key] = ''.$tag.''; /* put link back in tmp */
echo implode(",",$tmp);
Either this should work:
Tags: <?
// php5.3
$tags=explode(",", $line["m_tags"]);
$tags = array_map(function($tag){
return "<a href='http://www.yoursite.com/?tag=$tag'>$tag</a>";
}, $tags);
echo implode(", ", $tags);
?>
Here is how I would probably do it.
$str = "KEYWORD1,KEYWORD2,KEYWORD3";
$keywords = explode(',', $str);
$links = array();
foreach($keywords as $keyword) {
$links[] = "<a href='home'>$keyword</a>";
}
echo implode(', ', $links);
I have a PHP search script that queries a MySQL database and then parses the results through HTML to allow CSS styling. I want the script to highlight all of the keywords in the results that the user has search for. How can I do this with PHP?
My PHP script is:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult=mysql_query($searchSQL);
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<a href='{$row['url']}' class='webresult'><div class='title'>{$row['title']}</div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></a>";
}
if(empty($results)){
echo 'No results were found';
} else {
echo implode($results);
}
}
?>
Simplistically you could adapt the loop here:
$searchvar = trim($_GET['q']);
while ($row=mysql_fetch_assoc($searchResult)){
$description = str_replace($searchvar, '<span class="highlight">'.$searchvar."</span>", $row['description']);
$results .="<a href='{$row['url']}' class='webresult'>
<div class='title'>{$row['title']}</div>
<div class='desc'>{$description}</div>
<div class='url'>{$row['url']}</div></a>";
}
To make it a little better:
$searchvar = explode(" ", trim($_GET['q'])); //puts each space separated word into the array.
while ($row=mysql_fetch_assoc($searchResult)){
$description = $row['description'];
foreach($searchvar as $var) $description = str_replace($var, '<span class="highlight">'.$var."</span>", $description);
$description = str_replace($searchvar, '<span class="highlight">'.$searchvar."</span>", $row['description']);
$results .="<a href='{$row['url']}' class='webresult'>
<div class='title'>{$row['title']}</div>
<div class='desc'>{$description}</div>
<div class='url'>{$row['url']}</div></a>";
}
The benefit of the second one there is that if a user types in "ipod toudch yellow" you will be searching for "ipod", "toudch" and "yellow" which would negate the type and make the results more general.
You would need to exchange the single:
like '%query%'
with
foreach(explode(" ", trim($_GET['q']) as $searchvar) $where[] = "like '%$searchvar%'";
$wheresql = implode(" OR ", $where);
to get each search "word" to be looked for in the sql or you will have a limited search with a unrelated highlight.
i also found this solution to highlight each word of the results:
$text = $searchresults;
class highlight
{
public $output_text;
function __construct($text, $words)
{
$split_words = explode( " " , $words );
foreach ($split_words as $word)
{
$text = preg_replace("|($word)|Ui" , "<b>$1</b>" , $text );
}
$this->output_text = $text;
}
}
$highlight = new highlight($searchresults, $keywords);
echo $highlight;
In case that could help,
Regards,
Max
you can use regex or simply str replace to look for a particular string and add a span around it:
while ($row=mysql_fetch_assoc($searchResult)){
$str ="<a href='".$row['url']."' class='webresult'>";
$str .="<div class='title'>".$row['title']."</div>";
$str .="<div class='desc'>";
$str .= str_replace($query,"<span class='hightlighted'>".$query."</span>",$row['description']);
$str .="</div><div class='url'>".$row['url']."</div></a>";
$result[] = $str;
}
now the css:
span.highlighted {
background-color: yellow;
}
You can use str_replace. For each keyword the user uses, put it into the $search array, and also put it into a $replace array, but surround with with a classed span tag in the latter, which you can style with CSS later. For example:
$search = array('apple', 'orange');
$replace = array();
foreach ($search as $word)
{
$replace[] = "<span class='highlight'>$word</span>";
}
$string = str_replace($search, $replace, $string);
EDIT: assuming that $query just contains keywords delimited by a single whitespace, you could get the search array this way (with explode),
$search = explode(' ', $query);
Or, if you want to add more complex logic for processing the keywords out of the $query variable (like if you use query operators like +), you could use a for loop:
$queryTerms = explode(' ', $query);
$search = array();
foreach ($queryTerms as $term)
{
// do some processing of the $term (like delete "+"?)
// ...
$search[] = $processedTerm;
}