What are some best practices for extracting specific text patterns from log files using regex in PHP?

When extracting specific text patterns from log files using regex in PHP, it is important to first identify the pattern you are looking for and construct a regex pattern that matches it. Once you have the regex pattern, you can use functions like preg_match() or preg_match_all() to extract the desired text from the log file.

$log = "Error: File not found in /var/log/error.log";
$pattern = '/Error: (.*) in (.*)/';
if (preg_match($pattern, $log, $matches)) {
    echo "Error message: " . $matches[1] . "\n";
    echo "File path: " . $matches[2] . "\n";
} else {
    echo "Pattern not found in log file.";
}