How can regular expressions (PCRE) be utilized in PHP to manipulate FTP file listings?

Regular expressions (PCRE) can be utilized in PHP to manipulate FTP file listings by extracting specific information such as file names, sizes, and timestamps. By using regular expressions, we can parse the raw FTP listing data and extract the desired information for further processing or display.

<?php
// Example FTP listing data
$ftpListing = "drwxr-xr-x 2 user group 4096 Jan 1 12:00 file1.txt\r\n-rw-r--r-- 1 user group 1024 Jan 1 12:30 file2.txt\r\n";

// Regular expression pattern to extract file details
$pattern = '/([d-])((?:r|-)(?:w|-)(?:x|-)){3}\s+\d+\s+\w+\s+\w+\s+(\d+)\s+(\w{3}\s+\d{1,2}\s+\d{2}:\d{2})\s+(.+)/';

// Match file details using regular expression
preg_match_all($pattern, $ftpListing, $matches, PREG_SET_ORDER);

// Output matched file details
foreach ($matches as $match) {
    $fileType = $match[1];
    $permissions = $match[2];
    $size = $match[3];
    $timestamp = $match[4];
    $filename = $match[5];

    echo "File: $filename | Type: $fileType | Permissions: $permissions | Size: $size | Timestamp: $timestamp\n";
}
?>