我想使用php从字符串中获取一个子字符串的位置。我可以使用strpos(),但它只返回第一个匹配项。如何获取多次出现的位置。
发布于 2012-09-02 16:58:48
来自: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;
}这将返回一个包含实例位置的数组。
发布于 2012-09-02 16:59:34
从手册中,评论中有这样的功能。
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);
}
}发布于 2012-09-02 17:55:08
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;
} https://stackoverflow.com/questions/12234617
复制相似问题