Find Position Of Nth Occurrence Of String
The PHP strpos function and its relatives will find the first or last occurance of a string within a string. This is useful for using with functions such as substr() to get portions of strings for other purposes. However, there is no PHP function currently to get the position of the Nth occurance of a string. If you wanted to find the position of th e second occurance of a string within a string, or find the tenth occurance of a string within a string, this function will provide it.
By adding an offset to the function, a search can be made on as string using as search string and the numerical position of that occurance is returned.
EXAMPLE USAGE
Note in this example that the search string "is" occurs four times within the string to be searched. Two time as the word "is" and two times within the word "this". The third occurnce is at position 27 in the string.
<?php
/*** the third occurance ***/$offset = 3;
/*** the string to search for ***/$search = 'is';
/*** the string to search ***/$string = 'this is not a love song, this is not a love song';
echo strposOffset($search, $string, $offset);?>
0 comments:
Post a Comment