Reputation: 253
Right now I am working on a search function for my json decoded results
The code that I got looks like this:
<?php
foreach($soeg_decoded as $key => $val){
$value = $val["Value"];
$seotitle = $val["SEOTitle"];
$text = $val["Text"];
echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>';
}
?>
I want it to only show the results, which contains a specific word, which are stored in a variable named $searchText.
Is there any functions or commands, which can seperate all the results, and only show the results which contains the word stored in $searchText.
Something like this:
if($value OR $seotitle OR $text contains $searchText){
echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>';
}
Thanks in advance.
Upvotes: 2
Views: 1084
Reputation: 72269
You can do it by using strpos()
:-
if(strpos($value,$searchText) !== FALSE || strpos($seotitle,$searchText) !== FALSE || strpos($text,$searchText) !== FALSE){
echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>';
}
Upvotes: 3
Reputation: 7791
You can use substr_count()
<?php
foreach($soeg_decoded as $key => $val){
$value = $val["Value"];
$seotitle = $val["SEOTitle"];
$text = $val["Text"];
if(substr_count($value, $searchText) || substr_count($seotitle, $searchText) || substr_count($text, $searchText)){
echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>';
}
}
?>
Read more at:
Upvotes: 3
Reputation: 64687
This would probably be the simplest way to do it:
$row = '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>';
if (empty($searchText) || strpos($searchText, $row) !== false) {
echo $row;
}
This could have false matches if $searchText
contains <td>
or something, if you are concerned about that you could do:
if (count(array_filter([$value, $seotitle, $text], function($v) use ($searchText) {
return empty($searchText) || strpos($searchText, $v) !== false;
}))) {
echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>';
}
Upvotes: 3
Reputation: 111
You can use strpos string function to check if the $searchText (Needle) is part of $value/$seotitle/$text (Haystack).
if ((strpos($value,$searchText) !== false) or
(strpos($seotitle,$searchText) !== false) or
(strpos($text,$searchText) !== false))
{
echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>';
}
Upvotes: 3