Find position first occurence of an array of strings in a string
PHP has a function strpos()
for finding the position of the first instance of a given value in a string. Is there a way to do this with a needle that is an array of strings? It would give the first occurence:
$str = '1st and 3rd';
str_array_pos($str, array('st', 'nd', 'rd', 'th')) //would r开发者_Go百科eturn 1 because of 'st'
You could write one yourself:
function str_array_pos($string, $array) {
for ($i = 0, $n = count($array); $i < $n; $i++)
if (($pos = strpos($string, $array[$i])) !== false)
return $pos;
return false;
}
By the way, the return value in your example should be 0 and not 1 since array indices start at 0.
array_search() will do that, test with ===false
.
精彩评论