Reputation: 1
I need help with my PHP website. I need to search if textbox includes some text. Its working only on half. When I type "Kdy" it works but when I type "Kdy prijdes" it wont work. I need to change output when textbox includes some part of textbox but my idea wont work. Any solutions?
<h1>Zeptej se mě</h1>
<form id="frm" method="POST" action="?action">
<input type = "text" name = "textbox" value = ""/>
<input type="submit" value="Odešli" id="submit"/>
</form>
<?php
if(isset($_GET['action']))
{
$text = $_POST['textbox'];
$kde = array("kde", "Kde");
$kam = array("kam", "Kam");
$kdy = array("kdy", "Kdy");
$jak = array("jak", "Jak");
$co = array("co", "Co");
$proc = array("proč", "proc", "Proč", "Proc");
$kdo = array("kdo", "Kdo");
$koho = array("koho", "Koho");
if (in_array($text, $kde))
{
echo "Nikde";
}
elseif(in_array($text, $kam))
{
echo "Nikam";
}
elseif(in_array($text, $kdy))
{
echo "Nikdy";
}
elseif(in_array($text, $jak))
{
echo "Nevim";
}
elseif(in_array($text, $co))
{
echo "Nic";
}
elseif(in_array($text, $proc))
{
echo "Nevim";
}
elseif(in_array($text, $kdo))
{
echo "Nikdo";
}
elseif(in_array($text, $koho))
{
echo "Nikoho";
}
else
{
$text = array("Spíš ne", "Asi", "No nevím");
echo $text[array_rand($text)];
}
}
?>
Upvotes: 0
Views: 936
Reputation: 10163
You can use next simple function:
<?php
function find_text($text) {
// convert input text to lower case
$text = strtolower($text);
// build dictionary with responses on each word
$dict = [
"kde" => "Nikde",
"kam" => "Nikam",
"kdy" => "Nikdy",
"jak" => "Nevim",
"co" => "Nic",
"proč" => "Nevim",
"proc" => "Nevim",
"kdo" => "Nikdo",
"koho" => "Nikoho",
];
// loop trough dictionary
foreach($dict as $find=>$response) {
if (false !== strpos($text, $find)) {
// immediately return response when one of dictionary words found
return $response;
}
}
// if input cot contains no one of dictionary words return 'not found'
$text = array("Spíš ne", "Asi", "No nevím");
return $text[array_rand($text)];
};
// echo find_text('"Kdy prijdes"');
if(isset($_GET['action']))
{
echo find_text($_POST['textbox']);
}
?>
You can test PHP code here
Upvotes: 0
Reputation: 56
I would try to find a solution for this using strpos()
so if you check for a specific part of text it could look like this:
if(strpos($text, "Kdy") !== false){
//do something
}
Another approach could be to explode() the $text into its parts and compare the array with an array of strings you want to check for.
But there might be smarter solutions for this.
Upvotes: 1