How can regular expressions be effectively utilized in PHP to validate specific input formats, such as a 4-digit year or a string title?

Regular expressions in PHP can be effectively utilized to validate specific input formats by using the preg_match() function to check if the input matches the desired pattern. For example, to validate a 4-digit year, you can use the regular expression pattern '/^\d{4}$/' which checks for exactly 4 digits. Similarly, to validate a string title, you can use a pattern that allows letters, numbers, spaces, and certain special characters based on the requirements.

// Validate a 4-digit year
$year = "2022";
if (preg_match('/^\d{4}$/', $year)) {
    echo "Valid year format";
} else {
    echo "Invalid year format";
}

// Validate a string title
$title = "Hello World!";
if (preg_match('/^[a-zA-Z0-9\s\-\!\.\']+$/', $title)) {
    echo "Valid title format";
} else {
    echo "Invalid title format";
}