Good day!
Task: There is a text file. It is necessary to remove from it all words that are longer than N characters. The value of N is specified through the form. Check work on Cyrillic lines - find a mistake, find a solution.
I decided to break the task into smaller subtasks:
- Write the contents of the file to the string;
- Delete punctuation marks (delete everything except letters, numbers and spaces), double space;
- Split strings into words and write to an array;
Brute force array:
4.1 Screening words that are longer than the value of N;
4.2 Deletion of words from the text is longer than the value of N.
I haven't got further stuck on 4.2 yet. Apparently, I can't remove the substring from the string using the str_replace function.
Gives an error message:
E_COMPILE_ERROR : type 64 -- Cannot redeclare deleteWordsInFile() (previously declared in /home/ifiddlen/application/controllers/main.php(256) : eval()'d code:22) -- at line 58 The same kosovato performed:
2. Deletion of punctuation marks (delete everything except letters, numbers and spaces), double space, but this question is already secondary.
PS I'm a beginner, so the very way to solve this problem is crooked, is there a more “even” solution to this problem, who will advise what to do and what functions to use.
File code 03.php:
<html> <head> <title>Задание 3</title> <style> </style> </head> <body> <h3>3. Есть текстовый файл. Необходимо удалить из него все слова, длина которых превыщает N символов. Значение N задавать через форму. Проверить работу на кириллических строках - найти ошибку, найти решение. </h3> <form action="03.php" method="post"> <p> <lable for="first">Введите количество: </br></lable> </p> <input type = "text" id="first" name="num"> <input type="submit" value="Go!" /> </form> <?php //Функция удаления слов из файла. function deleteWordsInFile ($num) { //1.Запись содержимого файла в строку $text = file_get_contents('text.txt'); //Провераем что содержимое фала записано в строку. echo "<pre>"; var_dump($text); echo "</pre>"; //2.Удаление знаков препинания(удалить все кроме букв, цифр и пробелов), двойного пробела. //Удобный сервис надо не забыть "http://regexr.ru/". $content = preg_replace('/([^a-zа-я\s]|\s{2})/ui', "",$text); //echo "<pre>"; //var_dump($content); //echo "</pre>"; //Проверяем передалось ли значение через форму. echo "$num</br>"; //3. Разбитие строки на слова и запись в массив. $words = explode(" ", $content); $cutText = $text; //4. Перебор массива слов foreach ($words as $item){ //5. Отсеивание слов длинна которых больше значения N. if (mb_strlen($item) > 10){ var_dump($item); echo mb_strlen($item); echo "</br>"; //6. Удаление из текста слов длинна которых больше значения N. $cutText = str_replace("$item", "", $text); }; }; var_dump($cutText); }; if(array_key_exists('num', $_POST) && strlen($_POST['num']) > 0) { deleteWordsInFile($_POST['num']); }; ?> </body> </html> Text file text.txt:
Glorious cafe on the square Saint-Michel And then the weather turned bad. She changed one day - and the autumn ended. Because of the rain, we had to close the windows for the night, the cold wind tore the leaves from the trees in the Counterscarp. The leaves were soaked in rain, and the wind threw rain on a big green bus at the terminus, and the cafe for lovers was overcrowded, and the windows were fogging inside from heat and tobacco smoke. It was a gloomy cafe with a bad reputation, where drunks gathered from all over the quarter, and I didn’t go there because it smelled of sweat and sour wine. Men and women, regulars of the café For Lovers, were always drunk, or rather, drank as long as they had money, and they often drank wine that they bought half a liter or liter. Many aperitifs with strange names were advertised there, but few could afford them, except for a start, in order to get drunk as soon as possible. Drunk women were called poivrottes, which means "alcoholics."
deleteWordsInFilefunction a second time - DaVASrKincludethis script a couple of times, hence the error (most likely because of this). Think where it is possible and try to replace it withinclude_once, which it says in this case - DaVASrK