Xử lý tìm ký tự trong nhiều file đặt cùng một thư mục

Bài toán:

Muốn tìm chuỗi ký tự đặt trong nhiều file *.txt đặt cùng một thư mục

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class ConvertEbook extends Command {

    protected $signature = 'convert-ebook';

    protected $description = 'Send report via email';

    public function handle() {
        $pathsource = storage_path('Khong-Gia-Dinh.azw3');
        $pathdestination = storage_path('Khong-Gia-Dinh1.txt');
        if(!file_exists($pathdestination)){
            $command = 'ebook-convert '.$pathsource.' '.$pathdestination;
            echo shell_exec($command);  
        }
        $directory = storage_path();
                $files = glob($directory . '/*.txt');
        $searchTerm = 'chất khí hỗn hợp'; // Từ khóa tìm kiếm

        $searchTerm = " cho bài học in sâu vào tâm trí"; // Từ khóa tìm kiếm

        $files = glob($directory . '/*.txt'); // Danh sách các file txt trong thư mục

        $results = []; // Mảng lưu trữ các kết quả

        foreach ($files as $file) {
            $content = file_get_contents($file); // Đọc nội dung của file

            $positions = []; // Mảng lưu trữ vị trí tìm thấy

            // Tìm vị trí của từ khóa trong nội dung
            $position = strpos($content, $searchTerm);

            while ($position !== false) {
                $positions[] = $position; // Thêm vị trí vào mảng

                // Tìm vị trí tiếp theo của từ khóa trong nội dung
                $position = strpos($content, $searchTerm, $position + 1);
            }

            // Lấy đoạn văn bản trước và sau từ khóa cho từng vị trí tìm thấy
            foreach ($positions as $position) {
                $length = strlen($searchTerm); // Độ dài của từ khóa

                $start = max(0, $position - 400); // Vị trí bắt đầu
                $end = $position + $length + 400; // Vị trí kết thúc

                $snippet = substr($content, $start, $end - $start); // Đoạn văn bản trước và sau từ khóa

                $result = [
                    'file' => $file,
                    'snippet' => $snippet
                ];

                $results[] = $result; // Thêm kết quả vào mảng
            }
        }

        // Hiển thị các kết quả
        foreach ($results as $result) {
            echo "======================================================" . PHP_EOL;
            echo "File: " . $result['file'] . PHP_EOL;
            echo "Snippet: " . $result['snippet'] . PHP_EOL;
        }


        echo strlen(file_get_contents($pathdestination)).PHP_EOL;
        $this->info('Report sent successfully.');
    }
}

Related Posts