How can you ensure that a regular expression in PHP matches the beginning and end of a string?

To ensure that a regular expression in PHP matches the beginning and end of a string, you can use the caret (^) symbol to match the beginning of the string and the dollar sign ($) symbol to match the end of the string. This ensures that the regular expression will only match strings that start and end as specified.

$pattern = '/^start.*end$/';
$string = 'start middle end';
if (preg_match($pattern, $string)) {
    echo 'Match found!';
} else {
    echo 'No match found.';
}