I'm writing an IRC bot in PHP and trying to split the below notice down in to multiple parts.
:irc.server.com NOTICE PHPServ :*** CONNECT: Client connecting on port 6667 (class users): Guest!Guest@127.0.0.1 (127.0.0.1) [Guest]<br />
So far I am using:
while(1) {
while($data = fgets($socket)) {
echo nl2br($data);
flush();
$ex = explode(' ', $data);
if($ex[0] == "PING"){
fputs($socket, "PONG ".$ex[1]."
");
}
if($ex[1] == "NOTICE"){
if($ex[6] == "connecting"){
$userstring = $ex[12];
$usernick = strstr($userstring, '!', true);
$userip = strstr($userstring, '@');
}
}
}
}
?>
So $user.nick
is working ok but $user.ip
includes the @ and the IP address. Why does this include the @ but the nickname doesn't include the !?
Also how can I get $user.ident
which is between the ! and the @?
try:
$userParts = explode('@', $userstring);
$userip = end($userParts);
The reason is includes the '@' is because (source: http://php.net/strstr):
Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.
To solve this you could use substring like this:
$userstring = $ex[12];
$exPos = strpos($userstring, '!');
$atPos = strpos($userstring, '@');
$usernick = strstr($userstring, '!', true);
$userip = substr($userstring, $atPos + 1);
$userident = substr($userstring, ($exPos + 1), ($atPos - $exPos) - 1);
I left the first strstr because it's easier to read/understand than a substring call.