preg_match () does not extract all matches

2

I have this little PHP code:

<?php
$r = file("id.txt");
$content = implode(" ",$r);

if (preg_match('#"name":[^"]*"([^"]*)"#', $content, $datos)) {
    $mp = $datos[1];
} else {
    $mp = 'error';
}
echo $mp;

?>

That is responsible for opening and searching using preg_match () the content of

"name":"contenido"

with the help of regular expressions inside the "id.txt" file.

Content of "id.txt":

"name":"jose";
"name":"juan";
"name":"carlos";
"name":"luis";

There are more than 50 lines what it contains

"name":""

with different names.

Everything goes well. The detail is that it only gives me the first name and what I want is to get all the names and store them in a variable.

    
asked by BotXtrem Solutions 24.09.2017 в 05:33
source

1 answer

2

preg_match () returns only the first match.

To get them all, you should use preg_match_all () .

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags [, int $offset ]]] )


Code:

<?php
//comentado para que no haga falta el archivo
//$content = file_get_contents('id.txt'); 

//En cambio lo simulamos asignando el texto
$content = '"name":"jose";
"name":"juan";
"name":"carlos";
"name":"luis";';

if (preg_match_all('#"name":[^"]*"([^"]*)"#', $content, $resultado)) {
    $mp = $resultado[1];   //que sólo tome lo capturado por el primer grupo
} else {
    $mp = ['sin coincidencias'];
}

//var_export($mp);  //mostramos el resultado, también se podría usar un foreach

//Mostramos el contenido del array
foreach ($mp as $nombre) {
    echo $nombre . "<br>\n";
}

Result:

jose
juan
carlos
luis

Demo:

link

    
answered by 24.09.2017 / 05:47
source