How can regular expressions (regex) in PHP be utilized to ensure that subdomains adhere to domain naming conventions?

Regular expressions in PHP can be utilized to ensure that subdomains adhere to domain naming conventions by defining a pattern that matches valid subdomain names. This pattern can include rules such as allowing alphanumeric characters, hyphens, and periods, while ensuring that the subdomain does not start or end with a hyphen. By using the preg_match function with the defined regular expression pattern, we can validate subdomains against domain naming conventions.

$subdomain = "example-subdomain";
$pattern = '/^(?!-)[a-zA-Z0-9-]+(?<!-)$/';
if (preg_match($pattern, $subdomain)) {
    echo "Subdomain adheres to domain naming conventions.";
} else {
    echo "Subdomain does not adhere to domain naming conventions.";
}