How can you ensure that certain characters are not allowed at the beginning or end of a string in PHP?

To ensure that certain characters are not allowed at the beginning or end of a string in PHP, you can use the `preg_match` function with a regular expression pattern that checks for the specified characters at the start and end of the string. If the pattern matches, you can handle the error accordingly.

$string = "example_string";
$disallowed_chars = "/^[!@#\$%^&*].*[!@#\$%^&*]$/"; // Specify the disallowed characters within the square brackets

if (preg_match($disallowed_chars, $string)) {
    echo "Error: String cannot start or end with specified characters!";
} else {
    echo "String is valid.";
}