开发者

PHP: Splitting a string and printing

I have server output that looks like this

PLAYER_ENTERED name ipaddress username

If the string contains PLAYER_ENTERED there will always be 3 spaces within the string separating it (how can this be modified so it does this too?). I would like to print out only the ipaddress and username (last 2 sections). How can this be done?

This is cod开发者_如何学Ce that prints out the whole thing:

$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
    if (strstr($line, $q)) 
    {
        print "<li>$line"; 
    } 

I imagine this using explode() but I've given up trying since I hardily know how to code php.

Desired Output

username ipaddress


$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
    if (strstr($line, $q)) 
    {
        $data = explode(" ", $line); // split using the space into an array
                                     // array index 0 = PLAYER_ENTERED
        print "IP:" . $data[1];      // array index 1 = IP
        print "Name: " . $data[2];   // array index 2 = name
    }
}


You can use substr()to check if the first 14 characters of $line equals PLAYER_ENTERED and then you use list() and explode() to extract the data from the line.

$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while(($line = fgets($f)) !== FALSE)
{
    if(substr($line, 0, 14) == 'PLAYER_ENTERED'){
        list($event, $name, $ip, $username) = explode($string); // here they come!

        echo 'Name: ' . $name . ', ip: ' . $ip . ', username: ' . $username;
    }
}


try this ...

  <?
  $str = "PLAYER_ENTERED name 108.21.131.56 username";
    if ( preg_match( "~^(.+)\s+(.+)\s+([\d\.]+)\s+(.+)$~msi", $str, $vv ))
         echo $vv[3] .  " and " .$vv[4] ;
    else "N/A";
 ?>

IMHO Perl regexp - is the right Way to parse strings ...


One way would be:

$tokens = explode(' ', $line);
if (count($tokens) == 4 && $tokens[2] == $q) {
    printf('IP: %s Username: %s', $tokens[2], $tokens[3]);
}


<?php
$str = 'PLAYER_ENTERED name 108.21.131.56 username';

$data = explode(" ", $str )

print_r($data)

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜