Search futher if the amount of digits a number has is > 1 - php

I'm learning PHP and started a small project with some file handling involved, a database checker on numbers (to keep it simple). What I mean by that is when you type in a number and hit the submit button php is going to search through a text file to get a name by the number.
The text file looks like:
1 Sandra
2 Piet
3 Francis
etc...
The code:
<?php
// Type your code here
$val = $row = NULL;
if (isset($_POST["submit"])) {
$myFile = fopen("testData.txt","r");
$number = $_POST["input"];
$cntNumber = strlen($number);
while (!feof($myFile)){
$val = fgetc($myFile);
if (is_numeric($val)) {
if ($cntNumber > 1) {
// Point where I Don't know what to do
} elseif ($val == $number) {
$row = fgets($myFile);
}
}
}
}
?>
<div style="width: 232px; height: 100px; border: 1px solid gray; margin-bottom: 5px;">
<?php
echo $row . "<br>";
?>
</div>
<form action="index.php" method="post">
<input name="input" placeholder="Number" type="text">
<input name="submit" value="Search" type="submit">
</form>
So if the number has more than one digit it has to search for the next matching digit, but I don't know how I can achieve that. I hope my explanation was clear enough, if not don't mind asking some question's.
Thanks in advance

I don't know whether you want to use f-file functions, but simplier solution is:
if (isset($_POST["submit"])) {
$myFile = file("testData.txt");
// print_r $myFile and see that this is array of lines
$number = $_POST["input"];
// iterate over your lines:
foreach ($myFile as $line) {
// as each line contains two values divided by a space,
// you can explode the line into two parts
$parts = explode(' ', $line);
// print_r($parts) to see result
// next check first part which is number:
if ($parts[0] == $number) {
echo 'Found!';
break; // exit loop as your value is found
}
}
}
If you want to use f-file functions then code can be:
$fh = fopen("testData.txt", "r");
while(!feof($fh)) {
$str = fgets($fh, 1024);
$parts = explode(' ', $str);
// print_r($parts) to see result
if ($parts[0] == $number) {
echo 'Found!' . $str;
break; // exit loop as your value is found
}
}
But I strongly recommend you to use databases as storages.

Related

php csv skips one line on submit

There seems to be some issue with the code where the result is skipped with one line.
For example, if I write: 642641
the result should be: "642641","testgatan 1"
but instead, it's showing: "762755","testgatan 2"
How can I fix so it actually get the input submitted?
I got a link for you to see what I mean: http://snaland.com/herestheidnummer/test.html
Here's the csv:
ID,Gata
"642641","testgatan 1"
"762755","testgatan 2"
"346468","testgatan 3"
"114564","testgatan 4"
"758925","testgatan 5"
I used the php code from Find if a value exist in a CSV file with PHP by Fred -ii-
And modified it like this:
<?php
$search = $_GET['subject'];
$lines = file('http://snaland.com/herestheidnummer/anlaggningsnmr.csv');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (stripos($line, $search) !== FALSE);
}
if($line_number){
echo "Found result: " .$line;
}
else{
echo "Can't find result: " .$search;
}
?>
Html form:
<form name="form" action="http://snaland.com/herestheidnummer/verifiera.php" method="get">
<input type="text" name="subject" id="subject" value="000000">
<input type="submit" value="Submit">
</form>
Your problem is the condition in the while loop. The assignment to key and list get executed before the check of !$line_number. It should work ff you swap both conditions like this
while (!$line_number and list($key, $line) = each($lines) ) {
$line_number = (stripos($line, $search) !== FALSE);
}
Each advances the array cursor, so when you finde the result, the next value is already loaded. More here http://php.net/manual/en/function.each.php.
A simpler solution is to replace your loop with:
for($i = 0; $i<count($lines);$i++){
if(stripos($lines[$i], $search) !== false){
$line = $lines[$i];
break;
}
}
And on the if:
if($line){
echo "Found result: " .$line;
}

.txt date on HTML website, explode()

I've got a "data.txt" file with the following content:
One1:One2:One3:One4:One5:One6
Two1:Two2:Two3:Two4:Two5:Two6
Three1:Three2:Three3:Three4:Three5:Three6
Now I want to be able to take each data and put on a specific location of a htlm code. Each line for its own. So for the first line, it should look something like this:
<html>
<head>
<title></title>
<head>
<body>
<h1>One2</h1>
<h2>One4 some other Text One5</h2>
<img src="One6.jpg">
</body>
</html>
Unforturtunately I don't have a clue how to do that with explode(). Can anybody help me out or does someone know a good and easy tutorial?
Thanks a lot
Not completely sure if I got your question, but I think you want to first parse the data.txt line by line, THEN by the : delimiter.
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
foreach($lines as $line)
{
$split = explode(":", $line);
$s1 = $split[0];
$s2 = $split[1];
$s3 = $split[2];
echo '<h1>'.$s1.'</h1>';
echo '<h2>'.$s2.' lorem ipsum</h2>';
echo '<img src="'.$s3.'">';
}
Or would you like to output different content based on what line its currently reading from? Then something like:
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
$n = count($lines);
for($i=0; $i<$n; $i++)
{
$split = explode(":", $lines[$i]);
$s1 = $split[0];
$s2 = $split[1];
$s3 = $split[2];
if($i === 0)
{
echo 'First line in data.txt<br>';
}
elseif($i === 1)
{
echo 'Second line in data.txt<br>';
}
elseif($i === 2)
{
echo 'Third line in data.txt<br>';
}
else
{
echo 'All the other lines (which are currently not existing)<br>';
}
}
Just kind of guessing here, could need some more information to clarify the question :)

Improving the speed and efficiency of this PHP spellchecker

I built a simple PHP spellchecker and suggestions application that uses PHP's similar_text() and levenshtein() functions to compare words from a dictionary that is loaded into an array.
How it works: First I load the contents of the dictionary into an
array.
I split the user's input into words and spell check each of the
words.
I spell check by checking if the word is in the array that is the
dictionary.
If it is, then I echo a congratulations message and move on.
If not, I iterate through the dictionary-array comparing each word, in the dictionary-array, with the assumed misspelling.
If the inputted word, in lower-case and without punctuation, is 90%
or more similar to a word in the dictionary array, then I copy that
word from the dictionary array into an array of suggestions.
If no suggestions were found using the 90% or higher similarity
comparison, then I use levenshtein() to do a more liberal comparison
and add suggestions to the suggestions array.
Then I iterate through the suggestions array and echo each
suggestion.
I noticed that this is running slowly. Slow enough to notice. And I was wondering how I could improve the speed and efficiency of this spell checker.
Any and all changes, improvements, suggestions, and code are welcome and appreciated.
Here is the code (for syntax highlighted code, please visit here):
<?php
function addTo($line) {
return strtolower(trim($line));
}
$words = array_map('addTo', file('dictionary.txt'));
$words = array_unique($words);
function checkSpelling($input, $words) {
$suggestions = array();
if (in_array($input, $words)) {
echo "you spelled the word right!";
}
else {
foreach($words as $word) {
$percentageSimilarity = 0.0;
$input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
similar_text(strtolower(trim($input)), strtolower(trim($word)), $percentageSimilarity);
if ($percentageSimilarity >= 90 && $percentageSimilarity<100) {
if(!in_array($suggestions)){
array_push($suggestions, $word);
}
}
}
if (empty($suggestions)) {
foreach($words as $word) {
$input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
$levenshtein = levenshtein(strtolower(trim($input)), strtolower(trim($word)));
if ($levenshtein <= 2 && $levenshtein>0) {
if(!in_array($suggestions)) {
array_push($suggestions, $word);
}
}
}
}
echo "Looks like you spelled that wrong. Here are some suggestions: <br />";
foreach($suggestions as $suggestion) {
echo "<br />".$suggestion."<br />";
}
}
}
if (isset($_GET['check'])) {
$input = trim($_GET['check']);
$sentence = '';
if (stripos($input, ' ') !== false) {
$sentence = explode(' ', $input);
foreach($sentence as $item){
checkSpelling($item, $words);
}
}
else {
checkSpelling($input, $words);
}
}
?>
<!Doctype HTMl>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Spell Check</title>
</head>
<body>
<form method="get">
<input type="text" name="check" autocomplete="off" autofocus />
</form>
</body>
</html>
Levenshtein over a large list will be pretty processor intensive. Right now if you mistyped refridgerator it would calculate the edit distance to cat dog and pimple.
Too pare the list down before going into the levenstein loop you could match against a precalculated metaphone or soundex key for each of your dictionary entries. This would give you a much shorter list of likely suggestions then you could use levenshtein and similar_text as a means of rank the short list of matches.
Another thing that may help you out is to cache your results. I would venture to guess that most of the misspellings are going to be common.
The following implementation doesn't deal with the paring of the data effectively but it should give you some guidelines on how to dodge the levenshtein distance against the entire dictionary for each word.
First thing you are going to want to do is append the metaphone results to each of your word entries.
This would be a servicable way to do that
<?php
$dict = fopen("dictionary-orig.txt", "r");
$keyedDict = fopen("dictionary.txt", "w");
while ($line = fgets($dict)){
$line = trim(strtolower($line));
fputcsv($keyedDict, array($line,metaphone($line)));
}
fclose($dict);
fclose($keyedDict);
?>
Along with this you are going to need something that can read the dictionary into an array
<?php
function readDictionary($file){
$dict = fopen($file, "r");
$words = array();
while($line = fgetcsv($dict)){
$words[$line[0]] = $line[1];
}
return $words;
}
function checkSpelling($input, $words){
if(array_key_exists($input, $words)){
return;
}
else {
// sanatize the input
$input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
// get the metaphone key for the input
$inputkey = metaphone($input);
echo $inputkey."<br/>";
$suggestions = array();
foreach($words as $word => $key){
// get the similarity between the keys
$percentageSimilarity = 0;
similar_text($key, $inputkey, $percentageSimilarity);
if($percentageSimilarity > 90){
$suggestions[] = array($word, levenshtein($input, $word));
}
}
// rank the suggestions
usort($suggestions, "rankSuggestions");
return $suggestions;
}
}
if(isset($_GET['check'])){
$words = readDictionary("dictionary.txt");
$input = trim($_GET['check']);
$sentence='';
$sentence = explode(' ', $input);
print "Searching Words ".implode(",", $sentence);
foreach($sentence as $item){
$suggestionsArray = checkSpelling($item, $words);
if (is_array($suggestionsArray)){
echo $item, " not found, maybe you meant";
var_dump($suggestionsArray);
} else {
echo "found $item";
}
}
}
function rankSuggestions($a, $b){
return $a[1]-$b[1];
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Spell Check</title>
</head>
<body>
<form method="get">
<input type="text" name="check" autocomplete="off" autofocus />
</form>
</body>
</html>
The simplest way to do actual paring of the data would be to split your dictionary into multiple files partitioned by something like the first character in the string. Something along the lines for dict.a.txt, dict.b.txt, dict.c.txt etc.

Nested conditional using radio buttons to guide script in PHP

I've been working on this for a while and I can't seem to figure it out. I know it must be something really simple. Basically I have a script that works as a program that translates English to Piglatin, and it works fine, but I want the user to have a choice of whether or not to actually operate that script, by using a radio form with the text input that says "English" or "Piglatin". I've tried all different ways to get this to work, but using a nested conditional seems like it would be the most logical answer to me. However, whenever I try to run the script with it, it doesn't work. Can someone please tell me what I'm doing wrong?! It would be much appreciated. Thanks!
HTML Form:
<p><input type="text" name="original" size="20" maxlength="40" /></label></p>
<p><input type="radio" name="english" value="yes"/>english <input type="radio" name="english" value="no"/>piglatin</p>
<input type="submit" name="submit" value="submit" /></form>
PHP:
<?php # script
$original = $_REQUEST['original'];
$english = $_REQUEST['english'];
$array = explode(" ", $original);
if($english=="no")
{
piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$rest = substr($word,1,strlen($word)-1);
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1-way", $word);
}
elseif (preg_match('/^(th|sh)/', $word)) {
$word = preg_replace('/^(th|sh)(.+)$/', "$2-$1ay", $word);
}
else {
$word = preg_replace('/^[a-z](.+)$/', "$1-$first"."ay", $word);
}
$piglatin .= $word ." ";
echo $original ." becomes: ".$piglatin.".";
};
else
{echo $original.".";
};
?>
Like I said, I'm sure it's something really small and simple that I just can't see because I've been looking at the code so long. Any help is appreciated! Thank you!
Sort your indentation out and you will see your missing closing brackets.
<?php # script
$original = $_REQUEST['original'];
$english = $_REQUEST['english'];
$array = explode(" ", $original);
if($english=="no")
{
$piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$rest = substr($word,1,strlen($word)-1);
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1-way", $word);
} elseif (preg_match('/^(th|sh)/', $word)) {
$word = preg_replace('/^(th|sh)(.+)$/', "$2-$1ay", $word);
} else {
$word = preg_replace('/^[a-z](.+)$/', "$1-$first"."ay", $word);
}
$piglatin .= $word ." ";
echo $original ." becomes: ".$piglatin.".";
};
} else {
echo $original.".";
};

Php Unexpected T_FOR, expecting ). Creating multi-dimensional arrays using for()

here is my code. What I am trying to achieve is get text like this
Hola Hi
Pollo Chicken
Queso Cheese
and so on, and be able to make an array out of it such that
array[0][1] is Hi.
here is my code, the error is on line 13
<?php
if(isset($_POST['submit'])){
$message = $_POST['text'];
$words2 = explode("\r\n", $message);
$words = explode("\t", $words2[0]);
$numberoflines = count($words2);
echo $numberoflines;
for($i=0; $i<$numberoflines; $i++){
$words[$i] = $line;
$arrayline = explode("\t", $line);
$cow = array(
for($u=0; $u<2; $u++){
array($arrayline[$u])
}
);
}
}
?>
<html>
<form method = "POST" method ="changetext.php">
<textarea name="text">
</textarea>
<input type="submit" value = "Flip!" name="submit">
</form>
</html>
Maybe thats what you wanted to achieve ?!?
for($i=0; $i<$numberoflines; $i++){
$arraycols= explode("\t", $words[$i]);
foreach($arraycols as $col){
$list[$i][] = $col;
}
}
so Array $list is $list[row][col]
if i got right what is inside the $words Array. Your code is a little messi ;)
Try something like this:
$words = array();
if(isset($_POST['submit'])){
// Break down the text as lines:
$lines = explode("\r\n", $_POST['text']);
// For every line...
foreach($lines as $line){
// Seperate the 2 words (seperated by a tab)
$words[] = explode("\t", $line);
}
// Print the result:
var_dump($words);
}

Categories