简体   繁体   中英

substr method doesnt work with strpos in php

I have to make a php document, which takes apart an email adress. When you have sample@gmail.com for instance this should be shown:

local-part: sample

host: gmail

top-level-domain: com

when I run this code, the second statement doest work really well. Instead of "gmail" i get "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() . 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:

[$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. You want the latter to find the 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.

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.

Be careful when trying to parse emails. There are a lot of gotchas and obscure rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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