简体   繁体   English

substr方法不适用于php中的strpos

[英]substr method doesnt work with strpos in php

I have to make a php document, which takes apart an email adress. 我必须制作一个php文档,该文档将电子邮件地址分开。 When you have sample@gmail.com for instance this should be shown: 例如,当您有sample@gmail.com时,应显示:

local-part: sample 局部:样本

host: gmail 主持人:gmail

top-level-domain: com 顶级域名:com

when I run this code, the second statement doest work really well. 当我运行此代码时,第二条语句不能很好地工作。 Instead of "gmail" i get "gmail.com" 我得到的不是“ gmail”,而是“ gmail.com”

<?php $str=$_GET["email"];
echo "local-part: ".substr($str,0,strpos($str,"@"))."<br>";
echo "host: ".substr($str,strpos($str,"@")+1,strpos($str,"."))."<br>";
echo "top-level domain: ".substr($str,strpos($str,".")+1,strlen($str)); ?>
<form method="GET" action="index.php">
<input id="mail" type="text" size="20" name="email">
<input type=submit value="submit" name="submit">
</form>

I think this is easier and simpler to do with explode() . 我认为使用explode()更容易和更简单。 Split the first string on @ then split the right side of that on . @上拆分第一个字符串,然后在上拆分该字符串的右侧. :

$str = 'sample@gmail.com';
[$localPart, $domain] = explode('@', $str);
[$host, $tld] = explode('.', $domain);

echo "Local part: $localPart\n";
echo "Host: $host\n";
echo "TLD: $tld\n";

Output: 输出:

Local part: sample
Host: gmail
TLD: com

Note this only works when your domain is two levels. 请注意,这仅在您的域为两个级别时有效。 If you want to handle things like foo.gmail.com then you'll need a bit more: 如果您想处理foo.gmail.com类的foo.gmail.com那么您将需要更多:

[$localPart, $domain] = explode('@', $str);
$host = substr($domain, 0, strrpos($domain, '.'));
$tld = substr($domain, strrpos($domain, '.') + 1);

Output: 输出:

Local part: sample
Host: foo.gmail
TLD: com

Note strpos() finds the first occurrence from left-to-right, and strrpos() goes right-to-left. 注意strpos()从左到右查找第一个匹配项, strrpos()从右到左strrpos() You want the latter to find the TLD. 您希望后者找到TLD。

Another example: 另一个例子:

[$localPart, $domain] = explode('@', $str);
$parts = explode('.', $domain);
$tld = array_pop($parts); // pop off the last thing in the list
$host = implode('.', $parts); // re-join the remaining items

Alex's answer explains a better way to do this, but to answer your direct question, of why you're getting the ".com" with your host, the reason is that the substr() function accepts the length as its third argument, rather than the position to stop within the string. 亚历克斯的答案解释了一种更好的方法,但是要回答您的直接问题,即为什么用主机获取“ .com”,原因是substr()函数接受长度作为其第三个参数,而不是比在字符串中停止的位置。

If you run: 如果您运行:

echo strpos($str,".");

It will output the number 13. So your substr is trying to grab the 13 characters that follow the "@", as opposed to grabbing up to the 13th character in the string. 这将输出13号所以你SUBSTR试图抓住后面的 “@”,而不是抓住高达字符串中的第13个字符的13个字符。

Be careful when trying to parse emails. 尝试解析电子邮件时要小心。 There are a lot of gotchas and obscure rules. 有很多陷阱和模糊的规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM