Stacker
Stacker

Reputation: 157

Using PHP to Get Character Before the First Period?

I'm trying to figure out how to get the character before the first period in a domain.

For example, here's the character I'd want to extract and assign to a variable in each of these domains:

example.com - e
yahoo.com - o
example.co.uk - e
stackoverflow.com - w

Is there any simple way to do that? The only thing I can think of would be trying to extract all content before the first period and then get the last character from that string.

Upvotes: 0

Views: 508

Answers (3)

The fourth bird
The fourth bird

Reputation: 163277

Another way could be to use explode and substr

$char = substr(explode('.', "example.com", 2)[0], -1);

See a php demo

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

Since strings can be accessed by position, get the position minus 1 and access:

echo $string[strpos($string, '.') - 1];

Upvotes: 0

Mesar ali
Mesar ali

Reputation: 1898

you can use strpos and substr functions strpos - it'll return index of first occurrence of substring substr - return specific part of string

$domain='example.com';
$lastchar=substr($domain, strpos($domain,'.')-1, 1);

Upvotes: 1

Related Questions