简体   繁体   中英

Counting the number of times a substring occurs in a string using strlen+substr+strpos ONLY PHP

I would like to write a function that can count the number of times a substring occurs in a string using strlen+substr+strpos ONLY ,in PHP.

Without using substr_count !

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

Thanks Ahead

You will not need strlen() or substr() for this task.

Merely iterate your string with a while loop, advance the output of strpos() with every successful found needle and count the number of successful matches.

The "magic" in this technique is using the previous strpos() value (plus 1) as the the starting point for all subsequent strpos() calls.

Code: ( 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

A note to future readers, this question is not best practice. The correct method would be a simple call of the pre-existing php function substr_count() .

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

Or, less efficient versus substring_count() would be preg_match_all() which returns the number of matches.

 echo preg_match_all('/i/', 'iwritecodeiwritecodeiwritecode'); // 6
function fn($string, $char){ 
    $count=0;
    for($i=0; $i<strlen($string);$i++){
        if($string[$i] == $char){
            $count++;
        } 
    }
    print($count);
}

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

I hope it helps Cheers!

I've come up with my own best solution.

<?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");

?>

It doesn't only work for single character. You can also try passing two or more characters in the function like:

echo find_substr_count($str, "write");

I've given my best to help you.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM