String handling at alternate positions

Asked

Viewed 36 times

3

I have an output that via EXPECT access an equipment and receive 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  
                    ===============================================================================";

But depending on the equipment firmware the result comes with a few lines in different positions, however the Labels are always the same.

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

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

Does anyone have any idea how to do that?:

$result1 = preg_replace('!\s+!', ' ', $result1);
$posicao = strpos($result1, 'Service Id :');
$service_id_teste = substr($result1, $posicao+13, 4);
echo $service_id_teste;

3 answers

3

Follows 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 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

?>
  • Thank you very much Bruno, you helped a lot

3


You simply use REGEX:

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

Thus:

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

echo $ServiceIds['1'];

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

Upshot:

1311

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


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

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

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'];

Upshot:

9014
1311

Test this.

  • Perfect! Thank you

  • with the edition was better explained yet... thank you very much!

3

You can use a regex to capture the desired information:

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

The above passage says to marry Service Id followed by one or more spaces (\s+) followed by two points (:) 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
        )

)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.