Foreach preg_match_all

Asked

Viewed 91 times

3

I need to mount an array with all the data coming from another array using preg_match_all,I’m using the following code.

$results = array(
        'nome;26484865464864;ruadarua;desmontagem;sim;matogrosso;liberado',
        'fulanodetal;26469865464865;avenidadocentro;desmontagem;sim;matogrosso;liberado',
        'ciclano;26464065464866;ruasaojosegenonimo;desmontagem;sim;matogrosso;liberado'
    );

    foreach ($results as $value) {
        $cnpj_desmontagem[] = preg_match_all('/(\d{14})/', $value, $cnpj_desmontagem);
    }

    var_dump($cnpj_desmontagem);

But it is overriding the other values instead of mounting an array with all the data collected

  • Isn’t that the way out? https://ideone.com/eZ6KbV

  • no, if I stop the forech in the middle with a die it shows me the other values, the problem is that the assigned values are overlapping instead of mounting the array.

2 answers

3


preg_match_all() returns if the searched element was found, the capture is in the third argument. You can simplify this regex by removing the group ( ) and create a new variable to store the other values.

$results = array(
        'nome;26484865464864;ruadarua;desmontagem;sim;matogrosso;liberado',
        'fulanodetal;26469865464865;avenidadocentro;desmontagem;sim;matogrosso;liberado',
        'ciclano;26464065464866;ruasaojosegenonimo;desmontagem;sim;matogrosso;liberado'
    );

    $cnpjs = [];
    foreach ($results as $value) {
         if(preg_match_all('/\d{14}/m', $value, $m)) $cnpjs[] = $m[0][0];
    }

    print_r($cnpjs);

Exit:

Array
(
    [0] => 26484865464864
    [1] => 26469865464865
    [2] => 26464065464866
)
  • It worked perfectly, thank you very much, I was confusing the way to return and did not pay attention to the third parameter.

0

Good morning,

This function returns an integer, 0 if not found, 1 if it is just a occurrence etc

So try to do it this way

$results = array(
    'nome;26484865464864;ruadarua;desmontagem;sim;matogrosso;liberado',
    'fulanodetal;26469865464865;avenidadocentro;desmontagem;sim;matogrosso;liberado',
    'ciclano;26464065464866;ruasaojosegenonimo;desmontagem;sim;matogrosso;liberado'
);

foreach ($results as $value) {
    if (preg_match_all('/(\d{14})/', $value, $cnpj_desmontagem) > 0) {
        $cnpj_desmontagem[] = $value;
    }
}

var_dump($cnpj_desmontagem);

http://www.devfuria.com.br/php/o-basico-sobre-a-funcao-preg-match-all/

  • array:3 [▼
 0 => array:1 [▼
 0 => "26464065464866"
 ]
 1 => array:1 [▼
 0 => "26464065464866"
 ]
 2 => "ciclano;26464065464866;ruasaojosegenonimo;desmontagem;sim;matogrosso;liberado"
] It still returns me only the last value and also this time it returns me the entire array, I needed to clean it to just collect the Cnpjs.

Browser other questions tagged

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