How can I extract a word from a string that is enclosed between specific symbols?

Solution 1:

<?php
$str = 'http://example.abc.com';

// Split the URL into 3 parts: protocol, empty after //, and the rest (host + path)
$last = explode("/", $str, 3);

// Take the host part ("example.abc.com") and split by dot
$ans = explode('.', $last[2]);

echo $ans[0]; // Output: example
?>

Explanation:

explode(“/”, $str, 3) → breaks URL into [“http:”, “”, “example.abc.com”].

Index 2 gives us the domain (example.abc.com).

explode(‘.’, $last[2]) → breaks into [“example”, “abc”, “com”].

Index 0 is the subdomain/host prefix (example).

Solution 2 is a solid and more reliable approach since it uses PHP’s built-in parse_url().

Here’s a step-by-step breakdown:

<?php
// Build full URL dynamically (if needed)
$url = 'http'.((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '')
     .'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

// Or test with a fixed one
$url = 'https://www.example.foo.biz/';

// Extract the hostname (e.g., "www.example.foo.biz")
$hostName = parse_url($url, PHP_URL_HOST);

// Extract everything before the first dot (e.g., "www")
$host = substr($hostName, 0, strpos($hostName, '.'));

print_r($url);      // https://www.example.foo.biz/
print_r($hostName); // www.example.foo.biz
print_r($host);     // www
?>

✅ Why this is better than explode()

Works even if the URL has a path (/something/here) or query string.

Handles both http and https.

Less fragile compared to manual string splitting.

⚠️ One catch: this always grabs the first subdomain (e.g., www in www.example.com).
If you actually want example (the second part), you’d need:

$parts = explode('.', $hostName);
echo $parts[count($parts) - 2]; // example