note 28611 deleted from function.strpos by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 16:45:07 +0000 |
| Subject: | note 28611 deleted from function.strpos by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-154886@lists.php.net to get a copy of this message | ||
Note Submitter: arduenn at hotpop dot com
----
Hi all,
This function returns an array of positions (as integers) of a regular expression pattern that could
occur several times within a string (or FALSE if the pattern does not occur). Note that the function
is able to determine the positions of overlapping patterns. There may be shorter ways of determining
multiple pattern positions (such as by using 'explode') but likely these won't find
the overlapping patterns.
The multi_strpos function has one restriction (for the sake of snippet economy): if you use a
pattern starting with '\*' (backslash asterisk) a hit within the string will invoke an
infinite loop.
This function was initially written to create restriction maps of DNA sequences but you may find
other uses.
<?
function multi_strpos($pattern, $sequence) {
$n = -1;
while (ereg($pattern, $sequence)) {
$n++;
$fragment = split($pattern, $sequence);
$trimsize = (strlen($fragment[0]))+1;
$sequence = "*".substr($sequence, $trimsize);
$position[$n] = (strlen($fragment[0]) + $position[($n-1)]);}
return $position;}
// Below some code to demonstrate the function.
$testsequence = "She sells sea shells at the see shore.";
echo "Test sequence = '$testsequence'\n\n";
$testpattern = "s...s";
echo "Regular expression pattern = '$testpattern'\n\n";
$position = multi_strpos($testpattern, $testsequence);
if ($position) {
echo "Pattern match found at:\n";
while (list($index, $pos) = each($position)) {
echo "$pos\n";}}
?>