Skip to content
PHP Logo

How can regular expressions (regex) be used to extract information from external sources in PHP?

Regular expressions can be used in PHP to extract specific information from external sources, such as text files or web pages. By defining a pattern that matches the desired information, regex can be used to search through the source data and extract the relevant data. This can be useful for tasks such as scraping data from websites or parsing log files.

php
// Example of using regex to extract email addresses from a text file

// Read the contents of the text file
$fileContents = file_get_contents('example.txt');

// Define the regex pattern to match email addresses
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';

// Perform the regex match
preg_match_all($pattern, $fileContents, $matches);

// Output the extracted email addresses
foreach ($matches[0] as $email) {
    echo $email . "\n";
}