daihovey
daihovey

Reputation: 3575

removing @email.com from string in php

I want to just get the left half of an email address ( the username part of [email protected] ), so stripping the @ and any characters after it.

Upvotes: 15

Views: 16459

Answers (6)

yaser Mk
yaser Mk

Reputation: 1

function subStrEmail($Useremail)
{
    $emailSub=substr($Useremail,4);
    $email = explode('.', $emailSub);

    if($email[0]=='www'){
        $email=substr($emailSub,4);
        $email=ltrim($email,'www.');
        return $email;
    }
    return $emailSub;
}

Upvotes: 0

JohnP
JohnP

Reputation: 50019

you can split the string using explode()

$email = '[email protected]';
/*split the string bases on the @ position*/
$parts = explode('@', $email);
$namePart = $parts[0];

Upvotes: 2

jrn.ak
jrn.ak

Reputation: 36619

Since nobody's used preg_match yet:

<?php
    $email = '[email protected]';
    preg_match('/(\S+)(@(\S+))/', $email, $match);

/*  print_r($match);
        Array
        (
            [0] => [email protected]
            [1] => user
            [2] => @email.com
            [3] => email.com
        )
*/

    echo $match[1];  // output: `user`
?>

Using an array means if you decide later that you want the email.com part, you've already got it separated out and don't have to drastically change your method. :)

Upvotes: 0

Sourav
Sourav

Reputation: 17530

$text = '[email protected]';
$text = str_replace('@email.com','',$text);

Upvotes: -3

Shakti Singh
Shakti Singh

Reputation: 86386

$parts=explode('@','[email protected]');

echo $parts[0];// username
echo $parts[1];// email.com

Upvotes: 6

chriso
chriso

Reputation: 2552

If you have PHP5.3 you could use strstr

$email = '[email protected]';

$username = strstr($email, '@', true); //"username"

If not, just use the trusty substr

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

Upvotes: 30

Related Questions