Hello, task: Write a function that displays a list of files in a given directory that contain the search word. Directory and search word are set as function parameters. I wrote everything correctly, as I understand it in the preg_match () function, which should look for a match for a regular expression and return 1 if there is a match, it returns zero to me everywhere, although there is a file with such text, I can’t understand why the regular expression can compiled incorrectly, although it was checked on the site http://regexr.ru/ The following is the full php code:

<html> <head> <meta charset="utf-8"/> <title>Π—Π°Π΄Π°Π½ΠΈΠ΅ 5</title> <style> </style> </head> <body> <h3>5. ΠΠ°ΠΏΠΈΡΠ°Ρ‚ΡŒ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΡŽ, которая Π²Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ список Ρ„Π°ΠΉΠ»ΠΎΠ² Π² Π·Π°Π΄Π°Π½Π½ΠΎΠΉ Π΄ΠΈΡ€Π΅ΠΊΡ‚ΠΎΡ€ΠΈΠΈ, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ содСрТат искомоС слово. ДирСктория ΠΈ искомоС слово Π·Π°Π΄Π°ΡŽΡ‚ΡΡ ΠΊΠ°ΠΊ ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Ρ‹ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ. </h3> <form action="05.php" method="post" name="dir"> <h4>Π—Π°Π΄Π°ΠΉΡ‚Π΅ Π΄ΠΈΡ€Π΅ΠΊΡ‚ΠΎΡ€ΠΈΡŽ для Π²Ρ‹Π²ΠΎΠ΄Π° списка Ρ„Π°ΠΉΠ»ΠΎΠ²:</h4> <p><lable><input type="radio" name="dir_name" value="first_dir" checked> ΠŸΠ΅Ρ€Π²Π°Ρ дирСткория</lable></br> <p><lable><input type="radio" name="dir_name" value="second_dir"> Вторая дирСткория</lable></br> <p><lable><input type="radio" name="dir_name" value="third_dir"> Π’Ρ€Π΅Ρ‚ΡŒΡ дирСткория</lable></p> <p> <lable>ИскомоС слово: </br><input type="text" name="search" value="ΠΎΠ΄ΠΈΠ½"></lable> <input type="submit" value="Поиск" /> </p> </form> <?php //Ѐункция удалСния слов ΠΈΠ· Ρ„Π°ΠΉΠ»Π° function displayFilesListSearch ($dir, $search) { $files = glob($dir."/*.txt"); //Находим всС тСкстовыС Ρ„Π°ΠΉΠ»Ρ‹ Π² Π·Π°Π΄Π°Π½Π½ΠΎΠΉ Π΄ΠΈΡ€Π΅ΠΊΡ‚ΠΎΡ€ΠΈΠΈ foreach ($files as $file){ //echo "$search </br>"; if (preg_match("/\s[$search]\s/ui" ,file_get_contents($file))){ echo $file; }; }; }; //Услвоия выполСния if (array_key_exists('dir_name', $_POST) && strlen($_POST['dir_name'])){ displayFilesListSearch($_POST['dir_name'], $_POST['search']); }; ?> </body> </html> 

PS The file in the appropriate directory is created and the search word is present there, checked. Maybe it's in the encoding? In the file set utf-8 without BOM.

  • And what did strpos not suit you? - fens

1 answer 1

If I'm not mistaken, the preg_match function has a limit on the number of characters to be received from a source of 10,000 characters.

The search function itself is not quite correct: in what you now have, you are not looking for a word, but simply a set of some letters in an arbitrary order, which are limited by spaces on the sides. I would suggest doing this:

 if (preg_match("/\b($search)\b/msui", file_get_contents($file))){ echo $file; };