note 72466 deleted from function.strpos by levim
| From: | levim@php.net | Date: | Tue, 22 Jul 2014 03:26:45 +0000 |
| Subject: | note 72466 deleted from function.strpos by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-200009@lists.php.net to get a copy of this message | ||
Note Submitter: jamie at jamiechong dot ca
----
Try this function to find the first position of needle before a given offset.
For example:
<?php
$s = "This is a test a is This";
$offset = strpos($s, "test");
strnpos($s, "is", $offset); // returns 17
strnpos($s, "is", -$offset); // returns 5
// Works just like strpos if $offset is positive.
// If $offset is negative, return the first position of needle
// before before $offset.
function strnpos($haystack, $needle, $offset=0)
{
if ($offset>=0)
$result=strpos($haystack, $needle, $offset);
else
{
$offset=strlen($haystack)+$offset;
$haystack=strrev($haystack);
$needle=strrev($needle);
$result=strpos($haystack, $needle, $offset);
if ($result!==false)
{
$result+=strlen($needle);
$result=strlen($haystack)-$result;
}
}
return $result;
}
?>