在字符串中找到多个子字符串
答
来自:http://www.php.net/manual/en/function.strpos.php#108426
function strpos_r($haystack, $needle)
{
if(strlen($needle) > strlen($haystack))
trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);
$seeks = array();
while($seek = strrpos($haystack, $needle))
{
array_push($seeks, $seek);
$haystack = substr($haystack, 0, $seek);
}
return $seeks;
}
这将返回与OCCURENCES的位置的阵列。
答
从手册中,评论中有这样的功能。 strpos的
function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {
$offset = strpos($haystack, $needle, $offset);
if($offset === false) {
return $results;
} else {
$results[] = $offset;
return strpos_recursive($haystack, $needle, ($offset + 1), $results);
}
}
答
第三个参数,有$偏移,您可以使用:
$positions_of_string = array();
$str_to_find = "string to find";
$str_length = strlen($str_to_find);
$last_found = 0 - $str_length;
while(false !== $last_found) {
$last_found = strpos($the_string, $str_to_find, $last_found+$str_length);
if(false !== $last_found)
$positions_of_strings[] = $last_found;
}
此功能是越野车,当*针* *是*草垛的前缀为''strpos'returns 0'。 – Gumbo
非常感谢,它的工作很好。 –
没问题 - 请将此答案标记为已接受。 – Silox