【问题标题】:Return word from string containing @ php从包含 @php 的字符串中返回单词
【发布时间】:2017-02-28 16:37:02
【问题描述】:

我已经尝试了很长时间了,但没有成功

例如,我需要读取一个字符串并返回包含“@”的子字符串单词, 有一个字符串,如“andrew garfield 作为 andrew@gomail.com 被邀请” 希望函数返回子字符串“andrew@gomail.com”

尝试了explode、strpos、substr,以便找到@的位置,然后找到空格,然后explode不能真正让它工作 感谢您的帮助

【问题讨论】:

  • 首先,按空格展开,这样您就可以将单个单词放在一个数组中。然后,遍历数组并查看您的单词是否包含 at。如果是:返回它。仅此而已。

标签: php string


【解决方案1】:

我认为最适合您的解决方案是正则表达式。 这是给你的 PHP 代码:

$re = '/(?<=\b)\w([\w\.\-_0-9])*(@| at )[\w0-9][\w\-_0-9]*((\.| DOT )[\w\-_0-9]+)+(?=\b)/mi';
$str = 'andrew garfield invited as andrew@gomail.com';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);

【讨论】:

    【解决方案2】:

    获取所有此类子字符串的直接方法:

    $s = "andrew garfield invited as andrew@gomail.com or man@ohman.com";
    $ss = explode(" ", $s);
    $res = array();
    foreach($ss as $x) {
        if (strpos($x, "@") > -1) {
            array_push($res, $x);
        }
    }
    print_r($res);
    

    查看online PHP demo

    如果您更喜欢正则表达式,您可以将一个或多个非空白符号与\S+ 匹配,并使用\S+@\S+ regex 提取非空白块 + @ + 非空白块(最小长度为3):

    $s = "andrew garfield invited as andrew@gomail.com or man@ohman.com";
    $res = array();
    preg_match_all('~\S+@\S+~', $s, $res);
    print_r($res);
    

    要在末尾删除任何非单词字符,请在正则表达式末尾添加 \b。见this PHP demo

    注意:要从较长的字符串中获取电子邮件,您可以使用 Rob Locke 在How to get email address from a long string SO 线程中描述的方法。

    【讨论】:

      【解决方案3】:
      $result = array();
      $text_array = explode(' ', 'andrew garfield invited as andrew@gomail.com');
      
      for($i=0; $i<sizeof($text_array); $i++)
      {
          if(strpos($text_array[$i], '@'))
          {
              array_push($result, $text_array[$i]);
          }
      }
      
      echo "<pre>";
      print_r($result);
      echo "</pre>";
      

      【讨论】:

        【解决方案4】:

        保持简单:)

        $str = "andrew garfield invited as andrew@gomail.com";
        $strArr = explode('@',$str);
        $pieces = explode(' ', $strArr[0]);
        $last_word = array_pop($pieces);
        $email =  $last_word.'@'.$strArr[1];
        echo $email;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-03-14
          • 2018-06-23
          • 1970-01-01
          • 2018-05-14
          • 2016-12-06
          • 2012-03-15
          • 1970-01-01
          相关资源
          最近更新 更多