What best practices should be followed when using preg_match() in PHP to extract specific content from a string or resource?
When using preg_match() in PHP to extract specific content from a string or resource, it is important to follow best practices to ensure the correct extraction of the desired content. This includes using proper regular expressions to match the content accurately, handling potential errors or exceptions, and properly sanitizing the extracted content to prevent any security vulnerabilities.
// Example of using preg_match() to extract specific content from a string
$string = "Hello, my email is example@email.com";
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
if (preg_match($pattern, $string, $matches)) {
$email = $matches[0];
echo "Extracted email: " . $email;
} else {
echo "No email found in the string.";
}