How can the preg_match function be used to correctly identify a pattern in a string in PHP, especially when the pattern is anchored with ^ and $?

When using the preg_match function in PHP to identify a pattern in a string that is anchored with ^ (start of string) and $ (end of string), it is important to ensure that the entire string matches the pattern. This means that the pattern must match the entire string from start to end, rather than just a part of it. To achieve this, the pattern should be constructed in such a way that it covers the entire string without allowing for any additional characters before or after the pattern.

$string = "Hello, World!";
$pattern = "/^Hello, World!$/";

if (preg_match($pattern, $string)) {
    echo "Pattern matched successfully!";
} else {
    echo "Pattern did not match.";
}