A complete set of strn*pos functions that look for the nth occurrence of the needle in the haystack. I prefer this implementation of strnpos because it doesn't give visible warnings when supplied with a needle of length 0 (which is, admittedly, non-standard behavior). Based on a version I [originally posted on 05-MAR-2010]; this new version conforms more to the semantics of strpos.
<?php
function strnripos_generic( $haystack, $needle, $nth, $offset, $insensitive, $reverse )
{
if( ! is_string( $needle ) ) {
$needle = chr( (int) $needle );
}
$len = strlen( $needle );
if( 1 > $nth || 0 === $len ) {
return false;
}
if( $insensitive ) {
$haystack = strtolower( $haystack );
$needle = strtolower( $needle );
}
if( $reverse ) {
$haystack = strrev( $haystack );
$needle = strrev( $needle );
}
$offset -= $len;
do
{
$offset = strpos( $haystack, $needle, $offset + $len );
} while( --$nth && false !== $offset );
return false === $offset || ! $reverse ? $offset : strlen( $haystack ) - $offset;
}
function strnpos( $haystack, $needle, $nth, $offset = 0 )
{
return strnripos_generic( $haystack, $needle, $nth, $offset, false, false );
}
function strnipos( $haystack, $needle, $nth, $offset = 0 )
{
return strnripos_generic( $haystack, $needle, $nth, $offset, true, false );
}
function strnrpos( $haystack, $needle, $nth, $offset = 0 )
{
return strnripos_generic( $haystack, $needle, $nth, $offset, false, true );
}
function strnripos( $haystack, $needle, $nth, $offset = 0 )
{
return strnripos_generic( $haystack, $needle, $nth, $offset, true, true );
}
$haystack = 'Dit is een HoTtentotTentenTentenToonstellingTest!';
echo strnpos ( $haystack, 't', 5 ), ' === ', strnpos ( $haystack, 116, 5 ), PHP_EOL;
echo strnipos ( $haystack, 't', 5 ), ' === ', strnipos ( $haystack, 116, 5 ), PHP_EOL;
echo strnrpos ( $haystack, 't', 5 ), ' === ', strnrpos ( $haystack, 116, 5 ), PHP_EOL;
echo strnripos( $haystack, 't', 5 ), ' === ', strnripos( $haystack, 116, 5 ), PHP_EOL;
echo PHP_EOL;
echo strnpos ( $haystack, 'T', 5 ), ' === ', strnpos ( $haystack, 84, 5 ), PHP_EOL;
echo strnipos ( $haystack, 'T', 5 ), ' === ', strnipos ( $haystack, 84, 5 ), PHP_EOL;
echo strnrpos ( $haystack, 'T', 5 ), ' === ', strnrpos ( $haystack, 84, 5 ), PHP_EOL;
echo strnripos( $haystack, 'T', 5 ), ' === ', strnripos( $haystack, 84, 5 ), PHP_EOL;
?>