/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] displaying a snippet of the searched word

Good morning everyone (Manila Time).

I have a script here that searches the database based on a keyword. It works fine, searching and output, however the snippet wont work ($mess) I dont know what to put so I put the username it only prints the username. I want to print is like that of google. The string that appears below the link. Here is the code. Hope anyone helps me.

[code=php]<?php
include ‘db_connect.php’;
if(isset($_POST[‘submit’])){
$search = cleanString($_POST[‘search’]);
if(trim($search) == ”){
$errors = ‘<font color=”red”>Please enter a keyword</font><br /><br />’;
}
if($errors == ”){

$query = “SELECT * from users WHERE username LIKE ‘%$search%’ OR emailadd LIKE ‘%$search%’ OR firstname LIKE ‘%$search%’ OR midname LIKE ‘%$search%’ OR lastname LIKE ‘%$search%’ OR city_add LIKE ‘%$search%’ OR city_mobile LIKE ‘%search%’ OR prov_add LIKE ‘%$search%’ OR prov_mobile LIKE ‘%$search%’ OR bplace LIKE ‘%$search%’ OR age LIKE ‘%$search%’ OR weight LIKE ‘%$search%’ OR height LIKE ‘%$search%’ OR gender LIKE ‘%$search%’ OR citizenship LIKE ‘%$search%’ OR religion LIKE ‘%$search%’ OR cstatus LIKE ‘%$search%’ OR skin LIKE ‘%$search%’ OR eyes LIKE ‘%$search%'”;
$result = mysql_query($query) or die(mysql_error());
if($result){
display_form();
echo “<h1>found “. mysql_num_rows($result).” results</h1><br />”;
echo “<ul>”;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$mess=$row[‘username’];
$view = ‘page.php?id=’.$row[‘id’];
echo “<li><a href=”.$view.”>”.$row[‘firstname’].” “.$row[‘midname’].” “.$row[‘lastname’].'</a></li>’;
echo ‘<p style=”margin-right:100px;margin-top: 0px;”>’.snippet($mess, 200, true).'</p>’;
}
}
}
}

if(!isset($_POST[‘submit’]) || $errors != ”){
echo $errors;
display_form();
}

function display_form(){
?>
<form id=”search” action=”<?php $_SERVER[‘PHP_SELF’]; ?>” method=”post”>
Keyword: <input type=”text” name=”search” size=”30″ class=”text” /><br />
<input type=”submit” name=”submit” value=”Search” />
</form>
<?php
}
function snippet($text, $chars, $dots = false)
{
$end_char = substr($text, $chars, 1);
if(preg_match(‘#S#’, $end_char))
{
$chars += strpos($text, ‘ ‘, $chars) – $chars;
}
$ret = ($dots) ? substr($text, 0, $chars) . ‘…’ : substr($text, 0, $chars);
return $ret ;
}
?>[/code]

to post a comment
PHP

16 Comments(s)

Copy linkTweet thisAlerts:
@TimHJan 05.2010 — Good morning kingdm (London time),

If I understand correctly, you want $mess to show a short snippet of the text in the record, just like how Google shows a brief a snippet of the content of the page in its results. Is that right?

Just reading the value of $row['username'] into $mess will only give you the username to work with. Is there another field in the database that contains some text you wish to show a snippet of? Or do you want to show a snippet of many fields combined? (ie. "Username: x; Email: [email protected]; Name: John Smith...")
Copy linkTweet thisAlerts:
@kingdmauthorJan 05.2010 — Thank you for your reply TimH. (just call me Jen, i hate my username ?)

Yes that is exactly what's on my mind. A combination of fields in my database. How can I do it?
Copy linkTweet thisAlerts:
@TimHJan 05.2010 — Hi Jen,

What you need to do is similar to what you've already done in this line:

[code=php]echo "<li><a href=".$view.">".$row['firstname']." ".$row['midname']." ".$row['lastname'].'</a></li>'[/code]

Here you've put together someone's full name by combining the fields that make up the parts of his name.

So, in order to create something similar to the example I gave, you would combine several database fields and text strings to create a short summary of the data contained in the record. To do this, you would replace the $mess= line with the following lines:

[code=php]$mess="";
$mess .="Username: ". $row['username'] ."; ";
$mess .="Email Address: ". $row['emailadd'] ."; ";
$mess .="Gender: ". $row['gender'] ."; ";
$mess .="Age: ". $row['age'] ."; ";
$mess .="Address: ". $row['city_add'] ."; ";
$mess .="Citizenship: ". $row['citizenship'];[/code]


I've just included a few field in there (I didn't include the name, as it is already shown as the title of the result). You can add additional fields, or remove any of these as you like.

Hope this helps!
Copy linkTweet thisAlerts:
@kingdmauthorJan 05.2010 — Thanks Tim, you have reminded me of using the append. I didn't thought of that ?

I did it, and looks better, however can you suggest what to do if I want to make the string that matches the keyword into bold? I have this address field, its lenghty, say the only word that match on it is the work "carlington" st.

eg. I want it to display this way (address)

[I]Room 346 Atlanta Bldg. [B]Carlington[/B] St., Makati, Philippines[/I]

the Carlington is the only bold because it is the only match in the keyword.
Copy linkTweet thisAlerts:
@TimHJan 05.2010 — This will surround all instances of the search string with bold tags. It should be placed just after the larger $mess construction, as above:

[code=php]$mess = str_replace($search, "<b>". $search ."</b>", $mess);[/code]

HOWEVER!

This creates a bit of a problem for when you use your "snippet" function. First of all, the <b></b> tags increase the length of the string, so you won't get exactly 200 display characters. And secondly, because there is a possibility that the snippet function may cut the bold tags in half.

So, I would suggest calling the snippet function BEFORE the above. i.e.:

[code=php]$mess = snippet($mess, 200, true);
$mess = str_replace($search, "<b>". $search ."</b>", $mess);[/code]


...in that order. And then remove the function call on this line (so you don't call it again):

[code=php]echo '<p style="margin-right:100px;margin-top: 0px;">'.$mess.'</p>'; [/code]

Keep in mind that if you clip the string to 200 characters, and the search string appears outside the 200 character range, the bolded word won't show in the snippet.
Copy linkTweet thisAlerts:
@kingdmauthorJan 05.2010 — You're amazing mister, your the man ?

I fixed the snippet earlier, the one posted in here is already replaced. It works, however (lastly) hopefully, how can I disable the case sensitivity for matching? It won't bold if the keyword is carlington because in the database it's Carlington. If I input Carlington it would bold, magic, hehe ?
Copy linkTweet thisAlerts:
@TimHJan 05.2010 — Good point! This is easily done by changing the [b]str_replace[/b] call to [b]str_ireplace[/b] - the case-insensitive version of this function.
Copy linkTweet thisAlerts:
@kingdmauthorJan 05.2010 — Thank you so much TimH. I learned a lot of php today. ? I'm starting to love PHP.
Copy linkTweet thisAlerts:
@LetmeinJan 05.2010 — Php, is good powerful stuff, lol ?
Copy linkTweet thisAlerts:
@kingdmauthorJan 05.2010 — Php, is good powerful stuff, lol[/QUOTE]

More powerful than man? lol. :p

Uhm TimH, there is a bug in the str_ireplace(); it replaces the capitalization of the text if matches, I try to manipulate the code but the problem is above my knowledge in php, as a beginner I'm owned ?
Copy linkTweet thisAlerts:
@LetmeinJan 05.2010 — If you want the search term always capitolised, you can use...

[CODE]
$mess = istr_replace($search, "<b>" . ucwords(strtolower($search)) . "</b>", $mess);
[/CODE]


Or if you want to keep it, then I think (I havent put too much thought into this, so it might be wrong, lol)
[CODE]
$search2 = $search;
$mess = istr_replace($search, "<b>" . $search2 . "</b>", $mess);
[/CODE]
Copy linkTweet thisAlerts:
@DasherJan 05.2010 — A cleaner method of grabbing a snippet of an entry is to use wordwrap(). Using it will break at the end of a word. Using 200 characters will cut it at 200 or a little less depending on the length of the word that puts it over 200.

[code=php]
// something like...
$modtext = wordwrap($a_row['Introtext'],200,"|");
$shorttext = explode("|",$modtext);
$text = $shorttext[0];
[/code]


Also instead of searching everything for your search term why not but a selection-option box in to designate what the search term is. Search name, address, something else.

I have a little book club list that I have the option list of title, author, owner and then the search term. You select what you are searching for and then enter the search term. It makes for a little less of a $mess.
Copy linkTweet thisAlerts:
@TimHJan 05.2010 — Letmein - I suspect what Jen wants to do isn't to just capitalize the first letter of the search result in the snippet, but rather to have it retain its original capitalization.

To that end, I've found and slightly modified a function on php.net that will do exactly this.

Jen - this function requires PHP5 to run:

[code=php]function ext_str_ireplace($findme, $replacewith, $subject)
{
// Replaces $findme in $subject with $replacewith
// Ignores the case and do keep the original capitalization
// Required: PHP 5

$rest = $subject;
$result = '';

while (stripos($rest, $findme) !== false) {
$pos = stripos($rest, $findme);

// Remove the wanted string from $rest and append it to $result
$result .= substr($rest, 0, $pos);
$rest = substr($rest, $pos, strlen($rest)-$pos);

// Remove the wanted string from $rest and place it correctly into $result

$result .= str_ireplace($findme, substr($rest, 0, strlen($findme)), $replacewith);
$rest = substr($rest, strlen($findme), strlen($rest)-strlen($findme));
}

// After the last match, append the rest
$result .= $rest;

return $result;
}[/code]


Call it instead of [b]str_ireplace[/b], like so:

[code=php]$mess = ext_str_ireplace($search, "<b>". $search ."</b>", $mess);[/code]


Dasher - I think that in some practical use scenarios, you want to be able to apply your search term across multiple database fields. I'd say it's better to let SQL do the work, rather than to add another stage for the user!
Copy linkTweet thisAlerts:
@LetmeinJan 05.2010 — lmao, mate, I was going to modify the same function, but I got too lazy ? lol
Copy linkTweet thisAlerts:
@kingdmauthorJan 05.2010 — If you want the search term always capitolised, you can use...[/QUOTE]

Thanks for replying once again Letmein, and for introducing me the ucword() code. However, not all the searched word is capitalized, that's why I guess it's not suited. Anyway, thanks, because now I know what to do for any inputs that are in lower case such as firstname & lastname to be outputted in capitalized. ?

Also instead of searching everything for your search term why not but a selection-option box in to designate what the search term is. Search name, address, something else.[/QUOTE]

Yup you're right. I have that in mind, but as part of my everyday practice in learning PHP, it came across my mind to broaden the search function, I'm curious ?

To that end, I've found and slightly modified a function on php.net that will do exactly this.

Jen - this function requires PHP5 to run:
[code=php]function ext_str_ireplace($findme, $replacewith, $subject)
{
// Replaces $findme in $subject with $replacewith
// Ignores the case and do keep the original capitalization
// Required: PHP 5

$rest = $subject;
$result = '';

while (stripos($rest, $findme) !== false) {
$pos = stripos($rest, $findme);

// Remove the wanted string from $rest and append it to $result
$result .= substr($rest, 0, $pos);
$rest = substr($rest, $pos, strlen($rest)-$pos);

// Remove the wanted string from $rest and place it correctly into $result

$result .= str_ireplace($findme, substr($rest, 0, strlen($findme)), $replacewith);
$rest = substr($rest, strlen($findme), strlen($rest)-strlen($findme));
}

// After the last match, append the rest
$result .= $rest;

return $result;
}[/code]

[/QUOTE]


Thanks once more, TimH, you're my professor of the day ? I've seen this code in PHP.net, I played on it a while ago, but it owned me. ? Didn't know that an HTML tag can be placed inside the argument of a function. Now I know.
Copy linkTweet thisAlerts:
@LetmeinJan 05.2010 — Wouldnt having such a broad search cause problems though??? e.g What if the user wants people with Brown eyes, it would display everyone with a surname of "brown" and even "browne"??? age 18 would give everyone with an 18 in their phone number, etc ?
×

Success!

Help @kingdm spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...