在php中从字符串中删除@ email.com

时间:2011-04-01 06:11:17

标签: php

我想获取电子邮件地址的左半部分(username的{​​{1}}部分),以便删除@及其后的任何字符。

6 个答案:

答案 0 :(得分:15)

如果你有PHP5.3,你可以使用strstr

$email = 'username@email.com';

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

如果没有,请使用可靠的substr

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

答案 1 :(得分:2)

你可以使用explode()

拆分字符串
$email = 'hello@email.com';
/*split the string bases on the @ position*/
$parts = explode('@', $email);
$namePart = $parts[0];

答案 2 :(得分:1)

$parts=explode('@','username@email.com');

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

答案 3 :(得分:0)

由于还没有人使用preg_match

<?php
    $email = 'user@email.com';
    preg_match('/(\S+)(@(\S+))/', $email, $match);

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

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

使用数组意味着如果您稍后决定需要email.com部分,那么您已经将其分离出来并且不必彻底更改您的方法。 :)

答案 4 :(得分:0)

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;
}

答案 5 :(得分:-1)

$text = 'abc@email.com';
$text = str_replace('@email.com','',$text);