使用strlen + substr + strpos仅计算字符串中子字符串出现的次数

问题描述 投票:-2回答:3

我想编写一个函数,可以在PHP中使用strlen + substr + strpos来计算子字符串在字符串中出现的次数。

不使用substr_count

例如:fn('iwritecodeiwritecode-','i');

谢谢你

php string substr strpos strlen
3个回答
1
投票

你不需要strlen()substr()来完成这项任务。

只需用while循环迭代你的字符串,用每个成功找到的针推进strpos()的输出并计算成功匹配的数量。

这种技术中的“魔力”是使用先前的strpos()值(加1)作为所有后续strpos()调用的起点。

代码:(Demo

function countSubstrings($haystack,$needle) {
    $pos = -1;  // start at -1 so that first iteration uses $pos of 0 as starting offset
    $tally = 0;
    while (($pos = strpos($haystack, $needle, ++$pos)) !== false) {
        ++$tally;
    }
    return $tally;
}
echo countSubstrings('iwritecodeiwritecodeiwritecode', 'i');  // 6
echo countSubstrings('iwritecodeiwritecodeiwritecode', 'Perumal');  // 0
echo countSubstrings('iwritecodeiwritecodeiwritecode', 'write');  // 3

对未来读者的一个说明,这个问题不是最佳实践。正确的方法是简单调用预先存在的php函数substr_count()

echo substr_count('iwritecodeiwritecodeiwritecode', 'i');

或者,与substring_count()相比效率较低的是preg_match_all(),它会返回匹配数量。

echo preg_match_all('/i/', 'iwritecodeiwritecodeiwritecode'); // 6

0
投票
function fn($string, $char){ 
    $count=0;
    for($i=0; $i<strlen($string);$i++){
        if($string[$i] == $char){
            $count++;
        } 
    }
    print($count);
}

fn('iwritecodeiwritecode-','i');

我希望它有助于干杯!


0
投票

我想出了自己最好的解决方案。

<?php

    $str = "iwritecodeiwritecode";

    function find_substr_count($str, $substr) {
        $substr_len = strlen($substr);
        $substr_count = 0;
        for($i = 0; $i < strlen($str); $i++) {
            $substr_temp = '';
            for($j = $i; $j < $i + $substr_len; $j++) {
                if($j < strlen($str)) {
                    $substr_temp .= $str[$j];
                }
            }

            if($substr_temp == $substr) {
                $substr_count += 1;
            }
        }

        return $substr_count;
    }

    echo find_substr_count($str, "i");

?>

它不仅适用于单个字符。您还可以尝试在函数中传递两个或更多字符,如:

echo find_substr_count($str, "write");

我尽力帮助你。

希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.