"example@something.com" -> "example"


"example@something.com" -> "example" PHP

我对正则表达式很陌生,不能真正弄清楚它是如何工作的。我试过了:

function change_email($email){
   return preg_match('/^['w]$/', $email);
}

但是这只返回一个布尔值true或false,我希望它返回@之前的所有内容。这可能吗?我觉得我用错了php函数

尝试用更简单的方法处理explode:

explode('@', $email)[0];

使用strpos来获取@字符的位置,使用substr来裁剪电子邮件:

function change_email($email){
    return substr($email, 0, strpos($email, '@'));
}

例子:

<?php
function change_email($email){
    return substr($email, 0, strpos($email, '@'));
}
var_dump( change_email( 'foo@bar.com' )); // string(3) "foo"
var_dump( change_email( 'example.here@domain.net' )); // string(12) "example.here"
var_dump( change_email( 'not.an.email' )); // string(0) ""

你想使用的是strstr()函数你可以在这里阅读

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

RegEx

.*(?=@)

演示
$re = "/.*(?=@)/"; 
$str = "example@something.com"; 
preg_match($re, $str, $matches);

preg_match中有第三个参数,用于保存匹配的项。

,

preg_match( '/(?P<email_name>[a-zA-Z0-9._]+)@(?P<email_type>'w+)'.'w{2,4}/', $email, $matches );

If $email = 'hello@gmail.com'
$matches['email_name'] will be equal to "hello"
$mathces['email_type'] will be equal to "gmail"

注意邮件名称只能包含字母、数字、下划线和点。如果您想添加一些额外的字符,请将它们添加到字符类-> [a-zA-Z0-9]中。_其他字符]

通过正则表达式

<?php
$mystring = "foo@bar.com";
$regex = '~^([^@]*)~';
if (preg_match($regex, $mystring, $m)) {
    $yourmatch = $m[1]; 
    echo $yourmatch;
    }
?> //=> foo