Search code examples
phpreadfile

Read fails with spaces


I am very new to PHP and want to learn. I am trying to make a top-list for my server but I have a problem. My file is built like this:

"Name" "Kills"

"^0user1^7" "2"
"user2" "2"
"user3" "6"
"user with spaces" "91"

But if I want to read this with PHP it fails because the user has spaces. That's the method I use to read the file:

$lines = file('top.txt');
foreach ($lines as $line) {
    $parts = explode(' ', $line);
    echo isset($parts[0]) ? $parts[0] : 'N/A' ;
}

Maybe someone knows a better method, because this don't work very well :D.


Solution

  • You need REGEX :-)

    <?php
    
    $lines = array(
        '"^0user1^7" "2"',
        '"user2" "2"',
        '"user3" "6"',
        '"user with spaces" "91"',
    );
    
    $regex = '#"(?<user>[a-zA-Z0-9\^\s]+)"\s"(?<num>\d+)"#';
    
    foreach ($lines as $line) {
        preg_match($regex, $line, $matches);
        echo 'user = '.$matches['user'].', num = '.$matches['num']."\n";
    }
    

    In the regex, we have # delimiters, then look for stuff between quotes. Using (?PATTERN) gives you a named capture group. The first looks for letters etc, the second digits only.

    See here to understand how the regex is matching! https://regex101.com/r/023LlL/1/

    See it here in action https://3v4l.org/qDVuf