What are some best practices for using regular expressions in PHP to extract specific patterns from a string?

When using regular expressions in PHP to extract specific patterns from a string, it is important to use the appropriate regex functions and patterns to accurately match the desired content. Additionally, it is recommended to use regex modifiers to control the behavior of the pattern matching, and to properly handle any potential errors or exceptions that may arise during the extraction process.

// Example of using regular expressions in PHP to extract specific patterns from a string

$string = "Hello, my email is example@email.com and my phone number is 123-456-7890";

// Extract email address
if (preg_match('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', $string, $matches)) {
    $email = $matches[0];
    echo "Email address: " . $email . "\n";
}

// Extract phone number
if (preg_match('/\d{3}-\d{3}-\d{4}/', $string, $matches)) {
    $phone = $matches[0];
    echo "Phone number: " . $phone . "\n";
}