PHPを使用して、文字列から部分文字列の位置を取得したいと考えています。を使用できますstrpos()
が、最初に出現したものしか返されません。複数回出現する位置を取得するにはどうすればよいですか。
3 に答える
1
から: 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-02T08:58:48.210 に答える
0
strpos の 3 番目のパラメーターには、使用できる $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;
}
于 2012-09-02T09:55:08.343 に答える
0
マニュアルから、コメントにそのような機能があります。
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-02T08:59:33.973 に答える