【问题标题】:"example@something.com" -> "example" PHP“example@something.com” -> “示例” PHP
【发布时间】:2014-08-20 22:37:00
【问题描述】:

我对正则表达式非常陌生,无法真正弄清楚它是如何工作的。我试过这个:

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

但这仅返回布尔值 true 或 false,我希望它返回 @ 之前的所有内容。 这可能吗?我什至不认为我在这里使用了正确的 php 函数..

【问题讨论】:

  • explodesubstr 更适合这里。如果您有兴趣了解preg_match 函数,php 已经得到了世界上best documentations 之一。请参阅示例代码。如果您在 preg_match 调用中使用第三个参数,则匹配可用。
  • 电子邮件地址可能更复杂。虽然您不太可能在野外遇到一个,但请记住,一个电子邮件地址可能包含多个 @ 符号。 stackoverflow.com/a/12355897/362536
  • @user3465900 请接受对您有帮助的答案。如果您的问题得到了答案,请不要像这样不接受答案。

标签: php regex


【解决方案1】:

使用explode 尝试更简单的方法:

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

【讨论】:

  • 这对我有帮助,谢谢!你能解释一下这里发生了什么吗? [0] 代表什么?
  • @user3465900 explode函数返回一个数组,所以[0]返回该数组中的第一个元素。
【解决方案2】:

使用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) ""

DEMO

【讨论】:

  • 我喜欢健全性检查,以确保它至少具有@符号。
【解决方案3】:

您要使用的是 strstr() 函数,您可以阅读有关 here 的信息

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

【讨论】:

    【解决方案4】:

    正则表达式

    .*(?=@)
    

    Demo

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

    【讨论】:

      【解决方案5】:

      您在 preg_match 中有第三个参数,它保存匹配的项目。

      例如:

      preg_match( '/(?P&lt;email_name&gt;[a-zA-Z0-9._]+)@(?P&lt;email_type&gt;\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._ 其他字符]

      【讨论】:

      • 真实的电子邮件地址可以包含各种各样的东西......即使是引号内的空格!
      • @Brad 正如我所说,您可以根据需要添加其他字符。如果要留出空间,可以使用 [a-zA-Z0-9._\s]。无论如何,我不知道任何有空格的电子邮件地址。 :)
      • 同意,我只是把警告扔在那里。我一直在尝试使用user+whateveryouwant@gmail.com的Gmail功能,经常因为某人的正则表达式不完整而失败。
      【解决方案6】:

      通过正则表达式,

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 2012-06-21
        • 1970-01-01
        • 2013-06-21
        • 1970-01-01
        • 2014-05-02
        • 1970-01-01
        相关资源
        最近更新 更多