note 71513 added to function.strpos
| From: | Charles at osu1 dot php dot net | Date: | Sun, 03 Dec 2006 20:10:47 +0000 |
| Subject: | note 71513 added to function.strpos | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120254@lists.php.net to get a copy of this message | ||
Small improvement on the efforts of others:
<?php
function strpos_all($hs_haystack, $hs_needle, $hn_offset = 0, $hn_limit = 0) {
$ha_positions = array();
$hn_count = 0;
while (false !== ($pos = strpos($hs_haystack, $hs_needle, $hn_offset)) && ($hn_limit == 0
|| $hn_count < $hn_limit)) {
$ha_positions[] = $pos;
$hn_offset = $pos + strlen($hs_needle);
++$hn_count;
}
return $ha_positions;
}
function preg_pos($hs_pattern, $hs_subject, &$hs_foundstring, $hn_offset = 0) {
$hs_foundstring = NULL;
if (preg_match($hs_pattern, $hs_subject, $ha_matches, PREG_OFFSET_CAPTURE, $hn_offset)) {
$hs_foundstring = $ha_matches[0][0];
return $ha_matches[0][1];
}
else {
return FALSE;
}
}
function preg_pos_all($hs_pattern, $hs_subject, &$ha_foundstring, $hn_offset = 0, $hn_limit = 0)
{
$ha_positions = array();
$ha_foundstring = array();
$hn_count = 0;
while (false !== ($pos = preg_pos($hs_pattern, $hs_subject, $hs_foundstring, $hn_offset))
&& ($hn_limit == 0 || $hn_count < $hn_limit)) {
$ha_positions[] = $pos;
$ha_foundstring[] = $hs_foundstring;
$hn_offset = $pos + 1; // alternatively: '$pos +
strlen($hs_foundstring)'
++$hn_count;
}
return $ha_positions;
}
print_r(preg_pos_all('/s...s/', "she sells sea shells on the sea floor",
$ha_matches));
print_r($ha_matches);
?>
----
Server IP: 83.138.144.80
Probable Submitter: 82.153.5.20
----
Manual Page -- http://www.php.net/manual/en/function.strpos.php
Edit -- https://master.php.net/note/edit/71513
Del: integrated -- https://master.php.net/note/delete/71513/integrated
Del: useless -- https://master.php.net/note/delete/71513/useless
Del: bad code -- https://master.php.net/note/delete/71513/bad+code
Del: spam -- https://master.php.net/note/delete/71513/spam
Del: non-english -- https://master.php.net/note/delete/71513/non-english
Del: in docs -- https://master.php.net/note/delete/71513/in+docs
Del: other reasons-- https://master.php.net/note/delete/71513
Reject -- https://master.php.net/note/reject/71513
Search -- https://master.php.net/manage/user-notes.php