Search for string in text file and print after space occur in PHP

Solution:

By using , you are accepting partial matches, which causes 192.168.50.1 to match all your examples.

Instead, split the line on a space, and check for a full IP match. Then you can return the UP or DOWN part.

function pingAddress($ip) {
    // Read from file
    $lines = file('F:\share\result.txt');
    foreach($lines as $line){
        $parts = explode(' ', $line);
        if($parts[0] == $ip){
            return $parts[1];
        }
    }
}

echo pingAddress('192.168.50.1'); // nothing returned
echo pingAddress('192.168.50.105'); // UP

Answer

Solution:

Just add a "return;" after "echo $line;" The function stops, after the searched string is found.

function pingAddress($ip) {
    // Read from file
    $lines = file('F:\share\result.txt');
    foreach($lines as $line)
    {
        // Check if the line contains the string we're looking for, and print if it does
        if(strpos($line, $ip) !== false)
            echo $line;
            return;
    }
}

Answer

Solution:

You would need to check that there is a space after the IP address to ensure it is the full address and not part of another IP.

I've also changed this so that it reads the file a line at a time, so if it finds the IP address it stops reading there (and returns the UP or DOWN). This saves reading the entire file before searching...

function pingAddress($ip) {
    // Add space for search
    $ip .= ' ';
    $fp = fopen("a.csv", "r");
    while ( $line = fgets($fp) )
    {
        // Check if the line contains the string we're looking for, and print if it does
        if(strpos($line, $ip) !== false)
            return trim(substr($line, strlen($ip)));
    }
    fclose($fp);
    return '';
}

Source