0

请检查以下内容:

$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

有没有办法可以在没有 .com 的情况下返回 @example?

所以,基本上我需要在一个字符串中搜索一组我不知道的字符,这些字符存在于我知道的一组字符之间。

所以,在下面我想返回“狗”:

$string = "我曾经养过一只名叫spot的宠物狗";

我可以使用以下方法获取字符串的最后一部分:

$pet_type = strstr($string, 'pet ');

这可能吗?

4

8 回答 8

2

或使用 2 次爆炸

$email  = 'name@example.com';
        $email  = explode( '@', $email);
        $email = explode('.', $email[1]);

        $email = $email[0];
        echo $email;

返回:示例

于 2012-08-17T13:11:06.473 回答
1

您自己在标签中回答问题。使用regex/preg_match您可以查找模式并提取匹配的值。

这是正则表达式的介绍,它看起来很吓人但并不神圣,它很合乎逻辑:)

对于您的域示例,您可以执行以下操作:

preg_match("@[^\.]+", $email, $matches);
$domain = $matches[0];
于 2012-08-17T13:07:18.463 回答
0

尝试substr()结合strpos()

$start = strpos($email, '@');
$length = strpos($email, '.com') - $start;
$domain = substr($email, $start, $length);
于 2012-08-17T13:09:53.600 回答
0
$email = 'name@host.com';
$at_pos = strpos($email, '@');
$dot_pos = strpos($email,'.');
$domain_length = $dot_pos - $at_pos;
$domain = substr($email,$at_pos,$domain_length);
echo $domain;
于 2012-08-17T13:10:39.373 回答
0

我经常使用它,因为它使常规表达变得更加简单。您可以将 ^ 添加到 aa 范围以反转它。[^aeiou] 是除 a、e、i、o 和 u 之外的所有字符的第 th 范围。

对于您的示例,请尝试

@[^\.]+

这将匹配“@example”。

于 2012-08-17T13:11:57.840 回答
0

你可以试试:

$str = '';
$email  = 'name@example.com';
$domain = strstr($email, '@');
$domain = str_split($domain);
foreach($domain as $split){
$str .= $split;
if($split == '.'){
break;
}
}
echo $str; // prints @example

或者:

$email  = 'name@example.com';
$email = strstr($email, '@');
$email = explode(".", $domain);
echo $email[0]; // prints @example
于 2012-08-17T13:13:39.327 回答
0

你需要正则表达式

preg_match('/@(\w+)\.com/', $email, $match);
$domain = $match[1];

见:http ://www.php.net/manual/fr/book.pcre.php

基本上,在preg_match()调用中,我正在测试字符串$email是否具有以下序列:一个 at 符号,然后是使用括号 ( (\w+)) 在组中捕获的任何正数的单词字符,然后是一个点(转义 :)\.,最后是com. 如果匹配成功,则将捕获组放入$match数组中,并且可以使用它们从左到右的位置索引进行检索。

根据您在输入中期望的字符类型,可以改进匹配模式。总体而言,正则表达式比简单的字符串替换要慢,但功能要强大得多。值得学习它们的工作原理。

于 2012-08-17T13:17:33.633 回答
0
preg_match('/\@([a-zA-Z0-9-]+)?/', 'test@site-test.com', $matches);

Array ( [0] => @site [1] => site )

$matches[0]是你想要使用的。

于 2012-08-17T13:19:50.273 回答