What are some best practices for using regular expressions in PHP, especially when dealing with optional patterns?

When dealing with optional patterns in regular expressions in PHP, it is important to use the "?" quantifier to specify that a certain pattern may appear zero or one time. This allows for flexibility in matching strings that may or may not contain certain elements. Additionally, using capturing groups can help extract specific parts of the matched string when dealing with optional patterns.

// Example of using optional patterns in regular expressions in PHP
$string = "The color of the car is blue.";

// Match the optional word "car" before the color
if (preg_match('/(car\s)?(color)\sof\s(blue)/', $string, $matches)) {
    echo "Match found: " . $matches[0]; // Output: The color of blue
    echo "Optional word 'car' found: " . $matches[1]; // Output: car
}