Abhi
Abhi

Reputation: 5561

How to get a substring from string through PHP?

I want to change the displayed username from [email protected] to only abcd. For this, I should clip the part starting from @.

I can do this very easily through variablename.substring() function in Java or C#, but I m not aware with the syntax of PHP.

Suppose I'm having variable like:

$username = "[email protected]";
$username = {some string manipultion function}
echo $username; // abcd

Upvotes: 10

Views: 29185

Answers (6)

T.A.Chathura Priyahsad
T.A.Chathura Priyahsad

Reputation: 113

$crop_username = substr($username, 0, strpos($username, '@'));

This will help you

Upvotes: 0

Sander Marechal
Sander Marechal

Reputation: 23216

Try this:

$username = substr($username, 0, strpos($username, '@'));

Upvotes: 17

Wes
Wes

Reputation: 6585

list($username, $domain) = explode('@', '[email protected]')

Upvotes: 5

alex
alex

Reputation: 490143

Use strtok().

$username = strtok($email, '@');

CodePad.

Upvotes: 4

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

Use strstr function.

An example from the PHP reference -

<?php
    $email  = '[email protected]';
    $domain = strstr($email, '@');
    echo $domain; // prints @example.com

    $user = strstr($email, '@', true); // As of PHP 5.3.0
    echo $user; // prints name
?>

Upvotes: 5

Ibu
Ibu

Reputation: 43810

substr(string, 0, 20)

String, start, length

Upvotes: 2

Related Questions