61 votes

Comment rechercher dans un tableau avec preg_match ?

Comment rechercher dans un tableau avec preg_match ?

Exemple:

 <?php
if( preg_match( '/(my\n+string\n+)/i' , array( 'file' , 'my string  => name', 'this') , $match) )
{
    //Excelent!!
    $items[] = $match[1];
} else {
    //Ups! not found!
}
?>

8voto

Galen Points 20535

Utiliser preg_grep

 $array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);

5voto

Mahdi Bashirpour Points 1406
$haystack = array (
   'say hello',
   'hello stackoverflow',
   'hello world',
   'foo bar bas'
);

$matches  = preg_grep('/hello/i', $haystack);

print_r($matches);

Sortir

 Array
(
    [1] => say hello
    [2] => hello stackoverflow
    [3] => hello world
)

4voto

Logan Serman Points 11537

Vous pouvez utiliser array_walk pour appliquer votre fonction preg_match à chaque élément du tableau.

http://us3.php.net/array_walk

3voto

goat Points 17643
$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X