downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

preg_grep> <Fonctions PCRE
[edit] Last updated: Fri, 25 May 2012

view this page in

preg_filter

(PHP 5 >= 5.3.0)

preg_filterRecherche et remplace avec une expression rationnelle

Description

mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

preg_filter() est identique à preg_replace(), mais elle ne fait que retourner les occurrences trouvées (éventuellement transformées). Pour plus de détails sur le fonctionnement de cette fonction, voyez preg_replace().

Valeurs de retour

Retourne un tableau si le paramètre subject est de type tableau ou une chaîne de caractères autrement.

Si aucune corrurence n'est trouvée ou si une erreur survient, un tableau vide sera retourné lorsque le paramètre subject est un tableau ou NULL sinon.

Exemples

Exemple #1 Exemple de comparaison de preg_filter() avec preg_replace()

<?php
$subject 
= array('1''a''2''b''3''A''B''4'); 
$pattern = array('/\d/''/[a-z]/''/[1a]/'); 
$replace = array('A:$0''B:$0''C:$0'); 

echo 
"preg_filter renvoie\n";
print_r(preg_filter($pattern$replace$subject)); 

echo 
"preg_replace renvoie\n";
print_r(preg_replace($pattern$replace$subject)); 
?>

L'exemple ci-dessus va afficher :

preg_filter renvoie
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [7] => A:4
)
preg_replace renvoie
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [5] => A
    [6] => B
    [7] => A:4
)

Voir aussi



preg_grep> <Fonctions PCRE
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes preg_filter
sajina_99 at hotmail dot de 25-Sep-2011 07:07
As I had to work with PHP5.2.X and needed preg_filter I wrote a quick and dirty workaround.

<?php
 
if (!function_exists('preg_filter')) {
 
    function
preg_filter($pattern, $replace, $subject, $limit = -1 , &$count = null) {
   
      if(!
is_array($subject)) {
       
$noArray = 1 ;
       
$subject = array($subject);
      }

     
$preg = preg_replace($pattern, $replace, $subject, $limit,  &$count);

     
$diff = array_diff($preg, $subject);
     
      if(
$noArray == 1) $diff = implode($diff) ;

      return
$diff ;
     
    }
   
  }
?>
MrBertie 31-Dec-2010 02:35
Another way to filter an array, and simply return the matching items: preg_grep!
Eric Naeseth 17-Dec-2010 06:38
If you want to just filter an array based on a regular expression, without replacing any of the array values, try RegexIterator: http://us3.php.net/manual/en/class.regexiterator.php

 
show source | credits | sitemap | contact | advertising | mirror sites