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)];
}
}
?>
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.
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
Related
I have a database with 5000 entries of local area codes to separate the area code from a phone number string. Area Codes could be a part of other Area Codes. For example
0212 Solingen
02129 Haan
The Area Code of Solingen is a Part of the Area Code of Haan.
Question: Should i store all entries in an array or should i search directly in SQL till the final result?
Question: How can i get the entrie with the most found digits while area codes can be double in array / SQL
The Code i use is
The Result is "03491 52023" which is wrong; It should be "034915 2023"
<?php
$area_codes = array( '0350', '034', '034915', '03491', '0348', '0349', '03491', '034916', '034917',);
$phone = '0349152023';
foreach ($area_codes as $code) {
if (substr($phone, 0, strlen($code)) == $code) {
$phone_string = substr($phone, 0, strlen($code))." ".substr($phone, strlen($code));
}
}
if (!empty($phone_string)) {
echo $phone_string;
}
else {
echo "No AreaCode found.";
}
?>
Thanks for your help.
You just need to sort array and you will get desired output:
Working Demo: https://eval.in/871329
$area_codes = array( '0350', '034', '034915', '03491', '0348', '0349', '03491', '034916', '034917',);
sort($area_codes);
$phone = '0349152023';
foreach ($area_codes as $code) {
$subString = substr($phone, 0, strlen($code)); // stored in var so no need to re-code for substr
if ($subString == $code) {
$phone_string = $subString." ".substr($phone, strlen($code));
}
}
if (!empty($phone_string)) {
echo $phone_string;
}
else {
echo "No AreaCode found.";
}
Output:
034915 2023
i'm trying to use strpos or some sort of method to search for the word 'validated' within a textarea known as $likes and it'll return an error if not found. I wasn't sure how to get around validating two conditions (the textfield 'likes' cannot be empty and it must contain the word 'validation') so I kind of threw another if statement which didn't work and now I am desperately plugging it into my html..
Here's my basic php validation, I removed all my other error handling and left the textarea one.
<?php
// define variables + initialize
$nameErr = $likesErr = $placesErr = $thingsErr = $emaiLErr = $shopErr = $emailyesErr= "";
$name = $likes = $places = $email = $emailyes = $shops = $things = "";
$shops = array();
$things = array();
$likesErr2 = "Your likes must include the word 'validated'!";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//textarea likes
if (empty($_POST["likes"])) {
$likesErr = "Please tell me what you like about hiking! :(";
}
else {
$likes = $_POST["likes"];
}
}
?>
Here is my attempted us at strpos: :(
<label>What do you like about hiking?</label><span class = "error">* <?php echo $likesErr;?></span><br>
<textarea rows="4" cols="50" input type="text" id="likes" name="likes">
<?php echo $likesErr2 (if ((strpos($likes, "validated") === false)?></textarea>
My current setup is resulting in a 500 error so I feel like I'm definetly doing something wrong with the php.
EDIT
I have updated my php to this:
//textfield likes
if (empty($_POST["likes"])) {
$likesErr = "Please tell me what you like about hiking! :(";
}
else if ((strpos($likes, "validated") === false){
$likesErr2 = "Please include the word 'validated' in your likes textarea!";
}
else {
$likes = $_POST["likes"];
}
and html portion
<div>
<br><br>
<label>What do you like about hiking?</label><span class = "error">* <?php echo $likesErr; echo $placesErr2;?></span><br>
<textarea rows="4" cols="50" id="likes" name="likes"></textarea>
<br><br>
</div>
And I'm still getting a 500 error ):
Here's an example use of strpos:
<?php
$str = 'Time spent with cats is never wasted.';
if (strpos($str, 'dog') === FALSE) {
echo 'no dog';
}
echo (strpos($str, 'dog') === FALSE) ? 'no dog' : 'hot dog!';
// Outputs: 'no dogno dog'
I have the following PHP code
<?php
class SimpleEmailServiceMessage
{
public function properNames($formValue) {
$formValue = strtolower($formValue); //Make all letters small case
$formValue = ucwords($formValue); //Make all first letters capital
$formValue = str_replace('','',$formValue); //Remove extra spaces
if(is_numeric($username)) {
$error[] = 'The name is invalid';
}
return $error;
return $formValue;
}
}
$username = 'john doe';
$m = new SimpleEmailServiceMessage();
echo $m->properNames($username);
foreach($error as $result) {
echo $result . '<br>';
}
?>
I am managing to output $username, but I am not managing to output $error[] if it is a number. $error[] in my case is an array as different classes will have an error.
The current code is telling me Array Warning: Invalid argument supplied for foreach() in /web/com/140895582016925/main.php on line 22 which is for foreach($error as $result) {
The error message say it all: your $error is NOT an array.
Take a look at the is_numeric() validation part of your code.
You have an error there.
is_numeric() needs an argument.
In your case i think you need to:
if ( is_numeric($formValue ) )
{
// execute if condition
}
try this
<?php
class SimpleEmailServiceMessage
{
public $error;
public function properNames($formValue) {
$formValue = strtolower($formValue); //Make all letters small case
$formValue = ucwords($formValue); //Make all first letters capital
$formValue = str_replace('','',$formValue); //Remove extra spaces
if(is_numeric($formValue)) {
$this->error[] = 'The name is invalid';
}
return $formValue;
}
}
$username = 'john doe';
$m = new SimpleEmailServiceMessage();
echo $m->properNames($username);
if(isset($m->error))
{
foreach($m->error as $result) {
echo $result . '<br>';
}
}
?>
Demo
Try to use assignment:
$error = $m->properNames($username);
instead of echoing:
echo $m->properNames($username);
I have some code written in php to validate a postcode field in my form. The code is meant to check that the field is not empty (mandatory) and matches one of 5 usable postcodes, if not it displays an alert. The problem i am having is that when i leave the field empty and hit the submit button the proper alert is show but if i enter a wrong value and hit submit the form just loads to a blank screen, can anyone spot a mistake in my code? :
<?php
if (isset($_POST['submit'])) {
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "";
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
return true;
}
$msgp = '<span class="error"><b>Please enter correct postcode</b></span>';
return false;
} else if(empty($post)) {
$msgp = '<span class="error"><b>Please enter postcode</b></span>';
}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi">
<b>Post Code</b>
<br>
<input type="text" id="post" name="post" /><?php echo $msgp; ?>
</form>
return? Return where?
When you return in your main code, it's (nearly) the same as die()'ing.
So when you return, the remaining PHP won't be executed anymore.
I'd consider to set some variable like $success = true/false; instead of returning.
You return false after $msgp = '<span class="error"><b>Please enter correct postcode</b></span>'; therefor you do not continue to the form below... remove the returns from your code to be able to handle and show an error.
You are using return. Are you in a function() {} ? If so, all your variables are in function scope. You could do global $msgp; to make the variable accessible outside of the function.
If not... then you shouldn't use return.
Change php code to
<?php
if (isset($_POST['post'])) {
$post = intval($_POST["post"],0);
$words = array(2747,2750,2756,2760,2777);
$msgp = '<span class="error"><b>'.in_array($post,$words) ? "Please enter postcode" : "Please enter correct postcode" .'</b></span>';
}
There are a lot of things that can be simplified. For example codes as int array and using in_array() function. Return statement should be used to return something from method/function using it in global scope then execution of the current script file is ended. There is no need for it here. If there are more $words values you should consider using simple REGEX /[0-9]{4}/ and preg_match()
You want to display $msgp right? Use echo $msgp;. But you can return to nowhere in your code. (put it in a function).
Try this
<?php
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "<span class='error'><b>Please enter correct postcode</b></span>";
function check($post){
global $words;
$return=true;
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
//$return=true;
}
} else if(empty($post)) {
$return=false;
}
return $result;
}
$return=check($post);
if($return === true){
// echo you are right!
}
else {
echo $msgp;
}
my questions:
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result = array_search("你",$state);echo $result;
}else
{
echo "No Exists";
}
i expect the result of "1", however the output is "No Exists", i don't know why the program can't get the value of the key "你".
array_search will search the given array by value. Try the following:
$state = array("你"=>1);
if(array_key_exists("你", $state)) {
echo $state["你"];
} else {
echo "No Exists";
}
// => 1
» demo
Hope below function will help.
<?php
$array = array('arr1'=>array('find_me'=>'yes you did.'));
function get_value_by_key($array,$key)
{
foreach($array as $k=>$each)
{
if($k==$key)
{
return $each;
}
if(is_array($each))
{
if($return = get_value_by_key($each,$key))
{
return $return;
}
}
}
}
echo get_value_by_key($array,'find_me');
?>
the encoding type of the show paper and the store paper is GB2312.
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result1 = $state["你"];
echo $result1; // can get the value 111
}else
{
echo "No Exists";
}
the code above can be executed rightly. i can't show my problems accurately. Now i paste out my code , there is some questions.
<?php
$file = file("GB2312-HanZiBianMa.txt"); // file encoding type ANSI
foreach ($file as $line_num => $line)
{
list($no,$hex,$dec) = preg_split('[\t]',htmlspecialchars($line));;
$result[$hex] = $dec;
}
$result_2 = array_flip($result);
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}
foreach($result_2 as $k=>$each) //can get the value using the preg_match
{
if(preg_match('/你/', $k))
echo $k."\t".$each."<br/>";
}
?>
the format of GB2312-HanZiBianMa.txt is as follows:
1947 c4e3 你
1948 c4e4 匿
1949 c4e5 腻
1950 c4e6 逆
if your want to test the code , you can save the php code and save the GB2312.. file.
the question is:
why can't the following function get the right value ? the data comes from file and one stores together.
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}