Page 1 of 1

RegEx Help

Posted: Mon Jan 08, 2007 7:25 pm
by aliasxneo
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Here is my code:

Code: Select all

$handle = fopen("players.txt", "r");
while (!feof($handle)) {
    $file .= fread($handle, 1024);
}
fclose($handle);

$parts = explode("[player]", $file);

$players = array();
$index = 0;
foreach($parts as $part)
{
    while (preg_match("/[(.*)](.*)[\/.*]/", $part, $match))
    {
        echo "test";
        $players[$index][$match[1]] = $match[2];
        $index++;
    }
}
Here is the contents of players.txt:

Code: Select all

[player]
    [name]john1[/name]
    [kills]124[/kills]
    [deaths]345[/deaths]
[/player]
[player]
    [name]bob1[/name]
    [kills]342[/kills]
    [deaths]54[/deaths]
[/player]
I don't understand why this is not working. The file splits fine, and I get each user's individual stats in the array $parts. The problem is that preg_match() is not working, it won't even recognize it as a valid pattern. Can someone help me fix this pattern or explain what's wrong with it? Thanks.

P.S If you havn't noticed I'm trying to parse the user stats into an array.


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Mon Jan 08, 2007 7:30 pm
by Jhorra
Where is $match given a value?

Posted: Mon Jan 08, 2007 7:52 pm
by aliasxneo
In preg_match(). Look at php.net if you don't know what the function does.

Posted: Mon Jan 08, 2007 8:06 pm
by jayshields
I don't think you want to do a while(preg_match) because it won't loop through an array of results like you think, but anyway, isn't preg_match_all what you're after?

Posted: Mon Jan 08, 2007 8:28 pm
by aliasxneo
Yes, that would be a better method:

Code: Select all

foreach($parts as $part)
{
    if(preg_match_all("/[(.*)](.*)[\/.*]/", $part, $matches))
    {
        foreach ($matches as $match)
        {
            $players[$index][$match[1]] = $match[2];
        }
    }
    $index++;
}
But that's not the point of the post. The point is that the RegEx is not matching and I don't know why. Looking at the file contents my code should work fine, but it won't match anything.

Posted: Tue Jan 09, 2007 12:09 am
by aaronhall
You're aware that square brackets need to be escaped to be interpreted literally?