PHP/String/preg grep

Материал из Web эксперт
Перейти к: навигация, поиск

preg_grep

 
<?php
   $foods = array("pasta", "steak", "fish", "potatoes");
   $food = preg_grep("/^p/", $foods);
   print_r($food);
?>



preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.

 
Its syntax is: array preg_grep (string pattern, array input_array)
<?
$foods = array("pasta", "steak", "fish", "potatoes");
$p_foods = preg_grep("/p(\w+)/", $foods);
$x = 0;
while ($x < sizeof($p_foods)) :
   print $p_foods[$x]. "<br>";
   $x++;
endwhile;
?>



Quickly finding lines that match a pattern

 
<?
$pattern = "/\bo"reilly\b/i"; // only O"Reilly books
$ora_books = preg_grep($pattern, file("/path/to/your/file.txt"));
?>



Using preg_grep()

 
<?
$text=<<<TEXT
"asdf.asdf,asdf!asdf
TEXT;
$words = preg_split("/[",.!\s]/", $text, -1, PREG_SPLIT_NO_EMPTY);
$double_letter_words = preg_grep("/([a-z])\\1/i",$words);
foreach ($double_letter_words as $word) {
    print "$word\n";
}
?>