phpsubstringtext-filestext-extractionfile-read

Get substring between two markers in a specific line of a file


I'm trying to select a specific section of a specific line within a file.

For instance, I want to isolate the first line of text from a file and get the numeric value of rate without the trailing kbit text.

Sample file contents:

tc class add dev br-lan parent 1:1 classid 1:2 htb rate 100kbit ceil 100kbit
tc class add dev br-lan parent 1:1 classid 1:3 htb rate 200kbit ceil 200kbit
tc class add dev br-lan parent 1:1 classid 1:4 htb rate 300kbit ceil 300kbit

I would like to select the data between "rate " (notice the space after rate) and "kbit" based on the line number, then store it as a variable.

Expected Result:

Effectively, I would like to retrieve the results based on, for example; line 1:

100

Then store this value as a variable.

This won't work with substr, as shown here: http://php.net/manual/en/function.substr.php as the length of the integer retrieved may not always be the same length.

File path:

../etc/init.d/bandwidthlimiters/rulestest

Solution

  • <?php
    
    $output_arr=array();
    $handle = fopen("inputfile.txt", "r");
    if ($handle) {
    
        $i=1;
        while (($line = fgets($handle)) !== false) {
    
        $test_string=$line;
        $test_string=str_replace(" htb rate ","@@",$test_string);
        $test_string=str_replace("kbit ceil ","@@",$test_string);
    
        $tmp = explode("@@", $test_string);
        array_push($output_arr,$tmp[1]);
        $i++;
       }
    
        fclose($handle);
    } else {
        // error opening the file.
    } 
    
    echo $output_arr[2]
    
    ?>