How can regular expressions be utilized to extract a second-level domain from a host address in PHP?

Regular expressions can be utilized in PHP to extract a second-level domain from a host address by using a pattern that matches the desired domain structure. The regular expression pattern should target the domain name after the first dot and before the top-level domain (TLD). By using functions like preg_match() or preg_match_all(), we can extract the second-level domain from the host address.

$hostAddress = "www.example.com";
$pattern = '/(?<=\.)([\w-]+)(?=\.)/'; // Regex pattern to extract the second-level domain
preg_match($pattern, $hostAddress, $matches);
$secondLevelDomain = $matches[0];

echo $secondLevelDomain; // Output: example