PHP/String/preg split
Содержание
- 1 Calculating average word length
- 2 Discarding empty elements with preg_split()
- 3 How preg_split() can be used:
- 4 Limiting the number of returned elements with preg_split()
- 5 Parsing a date with preg_split()
- 6 preg_split() Flags
- 7 preg_split() function operates like split(), except that regular expressions are accepted as input parameters for pattern.
- 8 preg_split.php
- 9 Using preg_split()
- 10 Using preg_split() to Break Up Strings
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";
?>