I have a script that search's for the word in the file just fine, I would like to echo the line number it was found on.
Thank you.

<html>
<body>
<form name="form" method="post">

input: <input type="text" id="search" name="search_box"  style="background:#000006; color: #FF0000" />
</p>
                   </p><input type="submit" name="submit" value="submit" />


            </form>


    </body>
</html>


<?php
$path = 'users.txt';
$input = $_POST['search_box'];
$cookie_file_path=$path;
$minimum_length = 2;

if(isset($_POST['submit'])){
if (!strlen(trim($_POST['search_box']))){
echo "You must enter an input.";
} else {
if (strlen($_POST['search_box']) < $minimum_length) {
  echo 'The input is too short; minimum length is 2 characters.';
}
 else{

$file = file_get_contents($path);
    $SearchString = $input;
    $breakstrings = explode('/',$SearchString);

    foreach ($breakstrings as $values)
    {
        if(!strpos($file, $values))
        {
            echo $values." is NOT found\n";
        }
else{

echo $values." was found\n";
    }   }
}
}
}
?>

Recommended Answers

All 2 Replies

file_get_contents returns a string. So you could split on new lines and do the search line-by-line, or load with file() which returns an array.

Thank you pritaeas, now it works great.

<html>
<body>
<form name="form" method="post">

input: <input type="text" id="search" name="search_box"  style="background:#000006; color: #FF0000" />
</p>

                   </p><input type="submit" name="submit" value="submit" />


            </form>


    </body>
</html>

<?php
$input = $_POST['search_box'];
$file = file("users.txt");
$key = $input;
$found = false;
$minimum_length = 2;

if(isset($_POST['submit'])){
if (!strlen(trim($_POST['search_box']))){
echo "You must enter an input.";
} else {
if (strlen($_POST['search_box']) < $minimum_length) {
  echo 'The input is too short; minimum length is 2 characters.';
}
 else{



foreach ($file as $lineNumber => $line) {
    if (strpos($line,$key) !== false) {
       $found = true;
       $lineNumber++;
       break;
    }
}
if ($found) {
   echo "$key was Found at line $lineNumber";
} else {
echo "$key was not found";
}
}
}
}
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.