String handling in alternate positions

3

I have an output via EXPECT access to an equipment and I get the data below:

$result1 = "

                    ===============================================================================
                    Service Basic Information
                    ===============================================================================
                    Service Id        : 1311                Vpn Id            : 0
                    Service Type      : Epipe               
                    Description       : xxxxxxxx
                    Customer Id       : 1312                
                    Last Status Change: 06/11/2017 10:51:13 
                    Last Mgmt Change  : 03/24/2017 19:22:10 
                    Admin State       : Up                  Oper State        : Up
                    MTU               : 9014                
                    MTU Check         : Enabled             
                    Vc Switching      : False               
                    SAP Count         : 1                   SDP Bind Count    : 1
                    Uplink Type:      : MPLS                

                    -------------------------------------------------------------------------------
                    Service Access & Destination Points
                    -------------------------------------------------------------------------------
                    Identifier                               Type         AdmMTU  OprMTU  Adm  Opr 
                    -------------------------------------------------------------------------------
                    sap:lag-10:1311                          q-tag        9212    9212    Up   Up  
                    sdp:1019:1311 S(192.168.101.19)          n/a          0       9190    Up   Up  
                    ===============================================================================";

However depending on the firmware of the equipment the result comes with some lines in different positions, however the labels are always the same.

For example, I want to extract the values 1311 for Service Id and 9014 for MTU,

I tried with the following code to extract the Service Id, but the result with 4 characters (1311) if it is 5 characters (13211) is no longer working.

Does anyone have any idea how to do this?:

$result1 = preg_replace('!\s+!', ' ', $result1);
$posicao = strpos($result1, 'Service Id :');
$service_id_teste = substr($result1, $posicao+13, 4);
echo $service_id_teste;
    
asked by anonymous 12.06.2017 / 22:17

3 answers

3

You simply use REGEX:

Service Id\s+:\s?([0-9]+)

This way:

preg_match('/Service Id\s+:\s?([0-9]+)/', $result1, $ServiceIds);

echo $ServiceIds['1'];

\s+ is space, with any size, \s+? is an optional space, so :1234 and : 1234 are supported. In the end, there is [0-9]+ is any character between 0 to 9 of any size.

Result:

1311

The same can be done with any number, even if it is greater than 3 characters.

Copying the @ rray ♦ , where the answer uses | (or), which is really very good, and had not thought of this possibility, you can use:

preg_match_all('/(Service Id|MTU)\s+:\s?([0-9]+)/', $result1, $matches);

In this way, you can get the values using:

preg_match_all('/(Service Id|MTU)\s+:\s?([0-9]+)/', $result1, $matches);

$valores = array_combine($matches['1'], $matches['2']);

echo $valores['MTU'];
echo PHP_EOL;
echo $valores['Service Id'];

Result:

9014
1311

Test this.

    
12.06.2017 / 22:31
3

You can use a regex to capture the information you want:

Service Id\s+:\s+\d{4,5}|MTU\s+:\s+\d{4,5}

The above excerpt says to match Service Id followed by one or more spaces ( \s+ ) followed by colon ( : ) followed by 4 or 5 digits ( \d{2,5} ) or ( | ) marry MTU followed by one or more spaces ( \s+ ) followed by another 4 or 5 digits ( \d{4,5} )

preg_match_all('/Service Id\s+:\s+\d{4,5}|MTU\s+:\s+\d{4,5}/', trim($result1), $m);

echo "<pre>";
print_r($m);

Returns the following array:

Array
(
    [0] => Array
        (
            [0] => Service Id        : 1311
            [1] => MTU               : 9014
        )

)
    
12.06.2017 / 22:32
3

The following regular expression and explanations:

<?php

/*...*/
// Busca pela linha onde tem o Service Id, está com ignore case, então pega maiúscula e minuscula. Depois, procura por um número que pode ser de 0-9 repetidas vezes, sem limite e coloca este na posição serviceId do array.
preg_match_all('/Service Id.*?(?P<serviceId>[0-9]+)/i', $result1, $output);

// Imprime o primeiro item encontrado, volta como array, por isso o current para ir para o primeiro elemento
echo (current($output['serviceId'])); //1311

?>

I just forgot to include the MTU, below the example taking the two values and being named:

<?php

/*...*/
// Exemplo pegando 2 itens, service Id e Mtu.
preg_match_all('/(Service Id.*?(?P<serviceId>[0-9]+)|mtu.*?(?P<mtu>[0-9]+))/i', $result1, $output);

// Como os itens foram setados nomeados, basta acessá-los como abaixo. Caso tenha um terceiro item
// bastaria manter a sequencia.. Ex.: $output['qualquerCoisa'][2]..[3]..[4]..
echo $output['serviceId'][0]; //1311
echo $output['mtu'][1];       // 9014

?>
    
12.06.2017 / 22:31