PHP how to remove last separator? - php

I have tried a tons of variations, but I can't find the solution. Previously the output was like this:
word a
word b
word c
etc
I have changed some parts of code and now output is:
word a | word b | word c |
How to remove last separator?
The code is:
<div id="right">
<div id="synonyms">
<?
$separator = '<span class="pipe">|</span>';
$sql = mysql_query("SELECT DISTINCT word, id_word FROM words WHERE word LIKE '$word' ORDER BY word ASC LIMIT 100");
echo mysql_error();
while ($row=mysql_fetch_row($sql))
{
$word_synonym = $row[0];
$id_word_synonym = $row[1];
$sql2 = mysql_query("SELECT DISTINCT synonym, id_synonym FROM synonyms WHERE id_word = '$id_word_synonym' ORDER BY synonym ASC");
echo mysql_error();
$num_results =mysql_num_rows($sql2);
while ($row=mysql_fetch_row($sql2))
{
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
echo "".$separator."".$synonym." ";
}
}
?>
</div>
I tried to add $separator = substr($separator, -1, 0); and a lot of other suggestions, but without result.

My preference when doing something like this is to build an array of the strings, then use implode when outputting the final string. This is particularly useful because then I can do other things like merge groups, filter them, etc.

This was posted before and removed, but I think it's worth including as an optional method. Although I prefer Kolink's method, I've used this, too:
Use an iterator ($i) to identify the first (or last) item.
$i=0;
while ($row = mysql_fetch_row($sql2)) {
$i++;
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
echo ($i>1?$separator:"").'$synonym';
}
Not part of this answer, but here's an example of Kolink's (arguably superior) method:
$links=array();
while ($row = mysql_fetch_row($sql2)) {
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
$links[]='$synonym';
}
if (!empty($links)) {
echo implode($separator,$links);
}

Related

search array of words in database

I have text :
$a = I wanna eat apple , and banana .
I wanna get every words and punctuation of that sentence :
$b = explode(' ', strtolower(trim($a)));
the result of explode is array.
I have a words table on db that has fields : id, word and typewords all in lowercase. but for punctuation there are no exist in db.
I wanna search every words in db to take the type of words, so the final result that i want to get is :
words/typeofwords = I/n wanna/v eat/v apple/n ,/, and/p banana/n ./.
here's the code :
function getWord ($word){
$i = 0 ;
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
while ($row = mysql_fetch_array($query)) {
$word[$i] = $row['typewords'];
$i++;
}
return $word;
}
echo $b.'/'.getWord($b);
but it doesn't work, please help me, thanks !
Try with this:
function getWord($words){
$association = array();
foreach($words as $word)
{
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
if($row = mysql_fetch_array($query))
$association[$word] = $row['typewords'];
elseif(preg_match('/[\.\,\:\;\?\!]/',$word)==1)
$association[$word] = $word;
}
return $association;
}
$typewords = getWord($b);
foreach($b as $w)
echo $w.'/'.$typewords[$w];
function getWord($word){
// concat the word your searching for with the result
// http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
$query = mysql_query("SELECT CONCAT(word,'/',typewords) as this_result FROM words WHERE word = '$word' ");
$row = mysql_fetch_array($query);
return $row['this_result']." "; // added a space at the end.
}
// loop through the $b array and send each to the function
foreach($b as $searchword) {
echo getWord($searchword);
}
You assume the function parameter to be an array, but it is a string.
Edit: In your function you treat $word as an array as well as a string. Decide what you want and recode your function.

How would I sort this array [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to sort the results of this code?
Im making a search feature which allows a user to search a question and it will show the top 5 best matching results by counting the number of matching words in the question.
Basically I want the order to show the best match first which would be the question with the highest amount of matching words.
Here is the code I have.
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$search_count = str_word_count($search_term); //count words of string entered by user
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from
//user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found
{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
$percentage = '.5'; //percentage to take of search word count
$percent = $search_count - ($search_count * $percentage); //take percentage off word count
if ($matchingwords >= $percent){
$finalarray = array($title => $matchingwords);
foreach( $finalarray as $thetitle=>$countmatch ){
?>
<li><?php echo $thetitle ?><i> <br />No. of matching words: <?php echo $countmatch; ?></i></li>
<?php
}
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
When you search something it will show something like this.
Iv put the number of matching words under each of the questions however they are not in order. It just shows the first 5 questions from the database that have a 50% word match. I want it to show the top 5 with the most amount of matching words.
What code would I need to add and where would I put it in order to do this?
Thanks
Here's my take on your problem. A lot of things have been changed:
mysql_ functions replaced with PDO
usage of anonymous functions means PHP 5.3 is required
main logic has been restructured (it's really hard to follow your result processing, so I might be missing something you need, for example the point of that $percentage)
I realize this might look complicated, but I think that the sooner you learn modern practices (PDO, anonymous functions), the better off you will be.
<?php
/**
* #param string $search_term word or space-separated list of words to search for
* #param int $count
* #return stdClass[] array of matching row objects
*/
function find_matches($search_term, $count = 5) {
$search_term = str_replace("?", "", $search_term);
$search_term = trim($search_term);
if(!strlen($search_term)) {
return array();
}
$search_terms = explode(" ", $search_term);
// build query with bind variables to avoid sql injection
$params = array();
$clauses = array();
foreach ($search_terms as $key => $word) {
$ident = ":choice" . intval($key);
$clause = "`title` LIKE {$ident}";
$clauses []= $clause;
$params [$ident] = '%' . $word . '%';
}
// execute query
$pdo = new PDO('connection_string');
$q = "SELECT * FROM `posts` WHERE " . implode(' OR ', $clauses);
$query = $pdo->prepare($q);
$query->execute($params);
$rows = $query->fetchAll(PDO::FETCH_OBJ);
// for each row, count matches
foreach($rows as $row) {
$the_title = $row->title;
$the_title = str_replace("?", "", $the_title);
$title_terms = explode(" ", $the_title);
$result = array_intersect($search_terms, $title_terms);
$row->matchcount = count($result);
}
// sort all rows by match count descending, rows with more matches come first
usort($rows, function($row1, $row2) {
return - ($row1->matchcount - $row2->matchcount);
});
return array_slice($rows, 0, $count);
}
?>
<?php
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING);
$best_matches = find_matches($search_term, 5);
?>
<?php if(count($best_matches)): ?>
<ul>
<?php foreach($best_matches as $match): ?>
<li><?php echo htmlspecialchars($match->title); ?><i> <br/>No. of matching words: <?php echo $match->matchcount; ?></i></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<div id="search-status">No result found!</div>
<?php endif; ?>
Try adding asort($finalarray); after your $finalarray = array($title => $matchingwords); declaration:
...
if ($matchingwords >= $percent){
$finalarray = array($title => $matchingwords);
asort($finalarray);
....
It should sort your array Ascending by the Values

Remove last comma or prevent it from being printed at all MySQL/PHP

I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?
I did try to use rtrim, but I did not probably do it right.
This is my code as it is today:
<?php
$query0 = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()";
$result0 = mysql_query($query0);
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keyword = $row0['LCASE(ord)'];
echo "$keyword, ";
?>
I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )
$keyword = $row0['LCASE(ord)'];
$keywordc = "$keyword, ";
$keyword- = rtrim($keywordc, ', ');
echo "$keyword-, ";
As you might imagine, this did not print much (but at least it did not leave me with a blank page...)
I would do:
$keywords = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keywords[] = $row0['LCASE(ord)'];
}
echo implode(',', $keywords);
I usually do this by placing the results in an array first
$some_array = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {
$some_array[] = $row0['LCASE(ord)'];
}
then simply:
echo "My List: " . implode(', ', $some_array);
// Output looks something like:
My List: ord1, ord2, ord3, ord4
substr($string, 0, -1);
That removes the last character.

PHP mysql query judge and not echo the repeart part

I want to make a php search query. First, I put a sentence and explode every word get $name,Then I put $name make a query to match all the name which is exist in my database. Then echo part $row['name'][$i] has some word repeat.
for example: the sentence is :Marc Gasol is the brother of Pau Gasol and Gasol in my database, so the match words Gasol apearl 2 times. how to echo $row['name'][$i]; and get only one Gasol? thanks,
$query = mysql_query("SELECT * FROM books WHERE name like '$name[0]' OR name like '$name[1]' OR name like '$name[2]' OR name like '$name[3]' ");
$i = 0;
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
$sentence = "Marc Gasol is the brother of Pau Gasol";
$words = preg_split("/\s+/", $sentence);
//this will uniqueify your value set
$uniqueWords = array_keys(array_flip($words));
foreach($uniqueWords as $word){
$parts[] = "name like '%".mysql_real_escape_string($word)."%'";
}
$where = implode(" OR ", $parts);
$query = mysql_query("SELECT * FROM books WHERE $where ");
$i = 0;
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
You could run another quick loop through your array and remove all duplicate words before you proceed to executing your sql query that way you don't search the name twice in the first place. That should work if I am understanding what you are wanting to do.

PHP - Delete last 2 characters in a loop

I have the following which produces results for me.
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
echo $author['fullname'] .', ';
}
It prints it out perfect, except on the last run it still adds the comma and space, is there a way i can strip this from the last result, so its:
name, name, name, name
Instead of the following
name, name, name, name,
Cheers
A better way of doing this would be to separate out the handling of database results from the view/output logic, and then you can sidestep the issue all together, using implode to allow PHP to join each of your authors together into a single string, split by your delimiter of a comma and a space:
// your loop {
$authors[] = $author['fullname'];
}
// your output
echo implode(', ', $authors);
Just concate the data into a string and then remove the last 2 chars using
$author['fullname'] = substr($author['fullname'], 0, -2);
Refer the manual for substr http://php.net/manual/en/function.substr.php
Instead of echoing each author out you could put them in a string and then simply use trim() to take off the trailing comma and finally echo the whole string.
this will probably work
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
//echo $author['fullname'] .', ';
}
$name_count = count($author[]);
for($x=0;$x<$name_count ;$x++){
if($x == $name_count -1){
echo $author['fullname'];
}else{
echo $author['fullname'].", ";
}
}
the idea is to detect the last array index, so that we can apply all the commas after each name except to the last one.
don't ever echo inside foreach
$var = '';
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
$var .= $author['fullname'] .', ';
}
echo trim($var,', ');

Categories