note 28611 added to function.strpos

From: Date: Fri, 17 Jan 2003 22:45:35 +0000
Subject: note 28611 added to function.strpos
Groups: php.notes 
Request: Send a blank email to php-notes+get-42303@lists.php.net to get a copy of this message
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";}} ?> -- http://www.php.net/manual/en/function.strpos.php http://master.php.net/manage/user-notes.php?action=edit+28611 http://master.php.net/manage/user-notes.php?action=delete+28611 http://master.php.net/manage/user-notes.php?action=reject+28611

« previous php.notes (#42303) next »