when i have a search term in a form and then do :
If my search term is "test" it echos test 5 times?PHP Code:$keywordssplit = explode(" ", $keywords);
foreach ($keywordssplit as $keyword) {
echo $keyword;
}
![]()
| SitePoint Sponsor |
when i have a search term in a form and then do :
If my search term is "test" it echos test 5 times?PHP Code:$keywordssplit = explode(" ", $keywords);
foreach ($keywordssplit as $keyword) {
echo $keyword;
}
![]()





I don't know why that would happen.
When I run this:
I get one "test". Do a var_dump($keywords) before you explode it and see what's in it.PHP Code:<?php
$keywords = ' test ';
$keywordssplit = explode(" ", trim($keywords));
foreach ($keywordssplit as $keyword)
{
echo $keyword."\n";
}
?>
(Incidentally, you should trim the string before you give it to explode so you don't get empty elements returned in the array)
Thanks, Im assuming it's a problem with the get string and it putting in some dodgy objects so ill check it out, thanks for the advice i didnt know the vardump method.
I'm getting this from vardump :S
string(4) "test" string(4) "test" string(4) "test" string(4) "test" string(4) "test"
Trim doesn't solve it..
Even tried post from the form and still it's putting four or five in the variable![]()
OK fixed, it was inside the while loop so getting assigned 5 times due to 5 records, oops
Now the next problem, I'm trying to highlight keywords in the search results:
$keywordssplit var_dump for the search terms test manager isPHP Code:/* do replacing */
foreach ($keywordssplit as $keyword) {
$description = preg_replace ( "'($keyword)'si" , "<font color=\"red\">\\1</font>" , $row["description"]);
}
foreach ($keywordssplit as $keyword) {
$title = preg_replace ( "'($keyword)'si" , "<font color=\"red\">\\1</font>" , $row["title"]);
}
for some reason it only highights "manager" but not "test" in the results, any ideas?Code:array(2) { [0]=> string(4) "test" [1]=> string(7) "manager"





If you're using $description after the loop then you're only getting what the last assignment of $description is. In other words, $description gets a totally new value with each loop iteration, whatever was in the last iteration is lost.Originally Posted by Cavalli
Try this:
PHP Code:
$description = $row['description'];
foreach ($keywordssplit as $keyword) {
$description =
preg_replace ( "'($keyword)'si" , "<font color=\"red\">\\1</font>" , $description);
}
simple testing: do echo or print_r (depending on if it is array or string) before and after each action to see where it changes wrongly and then search for problem![]()
Got it, thanks lads.
Bookmarks