PHP/String/preg split

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

Calculating average word length

 
<?php
$word_count = $word_length = 0;
if ($fh = fopen("novel.txt","r")) {
  while (! feof($fh)) {
    if ($s = fgets($fh)) {
      $words = preg_split("/\s+/",$s,-1,PREG_SPLIT_NO_EMPTY);
      foreach ($words as $word) {
        $word_count++;
        $word_length += strlen($word);
      }
    }
  }
}
print sprintf("The average word length over %d words is %.02f characters.",
              $word_count,
              $word_length/$word_count);
?>



Discarding empty elements with preg_split()

 
<?
$text=<<<TEXT
"asdf.asdf,asdf!asdf
TEXT;
$words = preg_split("/[",.!\s]/", $text, -1, PREG_SPLIT_NO_EMPTY);
print "There are " . count($words) ." words in the text.";
?>



How preg_split() can be used:

 
<?php
    $s = "a , bc ,asdf";
    var_dump (preg_split ("/[ ,]/", $s));
?>



Limiting the number of returned elements with preg_split()

 
<?
$sea_creatures = "A;B, C,D, E; F";
$creature_list = preg_split("/, ?/",$sea_creatures, 3);
print "The last element is $creature_list[2]";
?>



Parsing a date with preg_split()

 
<?php $ar = preg_split("/[- :]/",$date);
var_dump($ar);
?>



preg_split() Flags

 
Reference Number               Value
 
PREG_SPLIT_NO_EMPTY            Causes empty substrings to be discarded.
 
PREG_SPLIT_DELIM_CAPTURE       Causes any references inside pattern to be captured and returned as part of the function"s output.
 
PREG_SPLIT_OFFSET_CAPTURE      Causes the position of each substring to be returned as part of the function"s output (similar to PREG_OFFSET_CAPTURE in preg_match()).



preg_split() function operates like split(), except that regular expressions are accepted as input parameters for pattern.

 
Its syntax is: array preg_split (string pattern, string string [, int limit [, int flags]])
If limit is specified, then only limit number of substrings are returned. 

<?
$user_info = "+J+++G+++++w";
$fields = preg_split("/\+{1,}/", $user_info);
while ($x < sizeof($fields)) :
   print $fields[$x]. "<br>";
   $x++;
endwhile;
?>



preg_split.php

 
<?php
   $delimitedText = "+A+++G+++++++++++C";
   $fields = preg_split("/\+{1,}/", $delimitedText);
    foreach($fields as $field) echo $field."<br />";
?>



Using preg_split()

 
<?
$sea_creatures = "A;B, C,D, E; F";
$creature_list = preg_split("/[,;] ?/",$sea_creatures);
print "Would you like some $creature_list[2]?";
?>



Using preg_split() to Break Up Strings

 
<?
$text = "a, o, p";
$fruitarray = preg_split( "/, | and /", $text );
print "<pre>\n";
print_r( $fruitarray );
print "</pre>\n";
?>