3

I am trying to create a search function to search a name in a data contain in txt file.

I have a data like this:

dimitri, 1998, php
nikolai, 1998, php
yuri, 1998, php
alyosha, 1998, php

I came up with an idea that to change this data to an array like this:

Array
(
    [0] => dimitri, 1998, php
    [1] => nikolai, 1998, php
    [2] => yuri, 1998, php
    [3] => alyosha, 1998, php
)

Then divide more to become multidimensional

Array
(
    [0] => dimitri
       Array(
           [0] => 1998
           [1]=> php
    [1] => nikolai
Array(
           [0] => 1998
           [1]=> php
    [2] => yuri
Array(
           [0] => 1998
           [1]=> php
    [3] => alyosha
Array(
           [0] => 1998
           [1]=> php
)

So that I can search name through key. Now I don't know what to do anymore. I try to use foreach() function to explode the value in an array, however it did not work, it created another problem, the array only display some characters.

Attempt

$array = array();
$split = explode('\n', file_get_contents($file));
foreach ($split as $content){
    $array = array_filter(array_map("trim", explode("\n", $content)));
    $array1 = array();
    $split2 = explode(", ", $array);
    foreach($array as $row){
        $array1[$row[1]][$row[2]][]=$row[0];
    }
}

HTML

<form action="search.php" method="POST">
    <input name="search_function" type="text" placeholder="Search who you want">
    <input type="submit" name="search" value="Search">
</form>

About my search, I am thinking to use post and if type correctly with data in search input, the data will display.

Beam291
  • 98
  • 7
  • 4
    This might help - https://stackoverflow.com/a/12315645/5284695 – Aakash Martand Apr 05 '19 at 09:35
  • Why are you trying to split this up at `\n` _two_ times? (Well you’re _trying_ only, because `'\n'` as you used in the first explode, is _not_ a newline character.) Your whole logic to read this into an array is way too complex - use `file` instead (be sure to pay attention to what the manual has to say about handling of line breaks), and take it from there. – 04FS Apr 05 '19 at 09:35
  • @AakashMartand I think that solution just only work if you have an array with key and value. I am having an array that contain a value contain many information that i to split out and that search can do, is that right? I am can't thinking any solution – Beam291 Apr 05 '19 at 09:47
  • Possible duplicate of [How to put string in array, split by new line?](https://stackoverflow.com/questions/1483497/how-to-put-string-in-array-split-by-new-line) – Tigger Apr 05 '19 at 09:54
  • Your datas seems to be in csv format. Put your datas in one variable (let's say $datas), and : `array_map('str_getcsv', explode('\n', $datas))` – Tmb Apr 05 '19 at 09:59
  • @ThomasMauduit-Blin no, it's just txt file – Beam291 Apr 05 '19 at 10:02

3 Answers3

1

You could try following

/* read data from text file, line by line */
$arr = []; // file contents go into this array
$handle = fopen('test.txt', 'r');
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $arr[] = explode(',', $line);
    }
    fclose($handle);
} else {
    echo 'error occured';
}

/* echo the form */
$form = <<<HEREDOC
<form action="#" method="POST">
    <input name="search_function" type="text" placeholder="Search who you want">
    <input type="submit" name="search" value="Search">
</form>
HEREDOC;
echo $form;

/* the search logic */
$found = false;
$count = 0; // count # of hits
if(isset($_POST['search'])) {
    foreach($arr as $key => $value) {
        foreach ($value as $key => $value) {
            if ($value == $_POST['search_function']) {
                $count++;
                $found = true;
                break 2;
            }
        }
    }
}
/* result */
$message = ($found === true) ? "found " . $_POST['search_function'] . " (" . $count . ") occurrence." : 'nothing found.';
echo $message;
jibsteroos
  • 1,366
  • 2
  • 7
  • 13
0

And a PHP example, multiple matching lines will be displayed:

<?php
$file = 'somefile.txt';
$searchfor = 'name';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}
Taha Zgued
  • 1,088
  • 12
  • 18
0

Your file seems to be in a CSV format (or at least its content is), so consider this piece of code :

$datas = array_map('str_getcsv', file($pathToYourFile));

It will convert your file into an array.

https://www.php.net/manual/fr/function.file.php https://www.php.net/manual/fr/function.str-getcsv.php

Tmb
  • 450
  • 12
  • 20