PHP代码
<?php /** * @description: 获取模式串在主字符串中的所有首字母出现索引位置(递归版) * @author: cutefrog(injection.mail@gmail.com) * @parameter: $mainstr 主字符串(必要参数) * @parameter: $modestr 模式串(必要参数) * @parameter: $mainpos 主字符串起始索引(可选参数) * @parameter: $modepos 模式串起始索引(可选参数) * @parameter: $matcheds 匹配到的索引数组(不需传入的参数,只作为递归时函数传递参数之用) * @return: $matcheds 如果非空返回匹配到的索引数组,否则返回-1 */ function myStrPos_recursive( $mainstr, $modestr, $mainpos = 0, $modepos = 0, $matcheds = array() ) { //若数组为空则返回-1,否则返回匹配到的数组 if( !isset( $mainstr[$mainpos] ) ) { return empty($matcheds)?-1:$matcheds; } //如果匹配到了就继续与模式串的下一个字符比较 if ( $modestr[$modepos] == $mainstr[$mainpos] ) { if ( !isset($modestr[$modepos+1]) ){ //将匹配结果加入数组 array_push( $matcheds, $mainpos - $modepos ); return myStrPos_recursive ( $mainstr, $modestr, ++$mainpos, 0, $matcheds ); } return myStrPos_recursive ( $mainstr, $modestr, ++$mainpos, ++$modepos, $matcheds ); } //否则回溯主串字符数组索引 else { return myStrPos_recursive ( $mainstr, $modestr, $mainpos-=$modepos-1, 0, $matcheds ); } } /** * @description: 获取模式串在主字符串中的所有首字母出现索引位置(迭代版) * @author: cutefrog(injection.mail@gmail.com) * @parameter: $mainstr 主字符串(必要参数) * @parameter: $modestr 模式串(必要参数) * @return: $matcheds 如果非空返回匹配到的索引数组,否则返回-1 */ function myStrPos_iteration( $mainstr, $modestr ) { $mainlen = strlen( $mainstr ); $modelen = strlen( $modestr ); $matchedpos = -1; $limit = 0; $matcheds = array(); for ( $mainpos = 0; $mainpos < $mainlen; $mainpos++ ){ for ( $modepos = 0; $modepos < $modelen; $modepos++ ) if ( $modestr[$modepos] == $mainstr[$mainpos] ){ if ( $modepos == ( $modelen - 1 ) ){ $matcheds[$limit++] = $mainpos - $modepos; break; } $mainpos++; } else { $mainpos = $mainpos - $modepos; break; } } return empty($matcheds)?-1:$matcheds; } $mainstr = 'dccabsccadsacca'; $modestr = 'cca'; print_r( myStrPos_recursive( $mainstr, $modestr ) ); print_r( myStrPos_iteration( $mainstr, $modestr ) ); ?>