How can regular expressions be effectively used to parse and extract data from a preformatted text/table in PHP?

Regular expressions can be effectively used to parse and extract data from a preformatted text/table in PHP by identifying patterns in the text that correspond to the data you want to extract. By creating a regular expression that matches the structure of the table, you can use functions like preg_match_all() to extract the desired data.

// Sample preformatted text/table
$text = "
| Name       | Age | Location    |
|------------|-----|-------------|
| John Doe   | 25  | New York    |
| Jane Smith | 30  | Los Angeles |
";

// Define the regular expression pattern to match the table structure
$pattern = '/\|(.+?)\|/';

// Use preg_match_all to extract data from the table
preg_match_all($pattern, $text, $matches);

// Display the extracted data
foreach ($matches[1] as $row) {
    $data = explode('|', trim($row));
    echo "Name: " . $data[1] . ", Age: " . $data[2] . ", Location: " . $data[3] . "\n";
}