查找字符串中多次出现的子字符串


find the multiple occurance of a substring in a string

我想使用php从字符串中获取子字符串的位置。我可以使用strpos(),但它只返回第一次出现。如何获取多次出现的位置。

来源: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;
}

这将返回一个带有出现位置的数组。

在手册中,注释中有这样的函数。

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);
    }
}

strpos的第三个参数,具有可以使用的$offset:

$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;
}