What are the best practices for filtering and extracting data from text using PHP?

When filtering and extracting data from text using PHP, it is important to use regular expressions to match patterns in the text and extract the desired information. One common approach is to use functions like preg_match() or preg_match_all() to search for specific patterns in the text and extract the relevant data. It is also important to sanitize the input data to prevent any potential security vulnerabilities.

// Example code to extract email addresses from a text using preg_match_all()

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Email me at john.doe@example.com or jane.smith@example.com for more information.";

$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
preg_match_all($pattern, $text, $matches);

$emails = $matches[0];

foreach ($emails as $email) {
    echo $email . "\n";
}