How can regular expressions be used effectively in PHP to manipulate and extract information from directory and file paths?

Regular expressions can be used effectively in PHP to manipulate and extract information from directory and file paths by using functions like preg_match() or preg_replace(). These functions allow you to search for specific patterns within the paths and extract or manipulate the desired information. By using regular expressions, you can easily extract file names, extensions, directories, or any other relevant information from paths.

$path = "/home/user/documents/file.txt";

// Extract file name and extension from the path
preg_match('/\/([^\/]+)\.([^\.]+)$/', $path, $matches);
$file_name = $matches[1];
$extension = $matches[2];

echo "File name: $file_name\n";
echo "Extension: $extension\n";