简体   繁体   中英

PHP count amount of letters in a substring match

I have a string and three sub strings:

$str = "smartphones";

$substr1 = "smart";
$substr2 = "phon";
$substr3 = "smartphone";

running the three substrings through a function should return 5, 4 and 10 respectively. If there's no match, it should return 0.

EDIT:

Also, if the string is "smartphones and other phones", $substr2 should still return 4, not 8

$str = "smartphones";

$substr1 = "smart";
$substr2 = "phon";
$substr3 = "smartphone";

if (false !== strpos($str, $substr1)) {
    echo strlen($substr1); // same with other substrings
}

You can use strpos() function to find the first occurrence of the substr and then just return the length of the substr.

function substrMatched($str, $substr){
    $res = strpos($str, $substr);
    if($res === false)
        return 0;
    return strlen($substr);
 }

Well, given Answer above was not exactly what you wanted:) I'd solve it like that:

    //Code snipplet with iteration

    $str = "smartphones phone";

    $substr1 = "smart";
    $substr2 = "phon";
    $substr3 = "smartphone";

    $substr_array[] = $substr1;
    $substr_array[] = $substr2;
    $substr_array[] = $substr3;


     foreach ($substr_array as $substr) {
       if($str[strpos($str,$substr,0)]!= " "){
       echo substr_count($str,$substr). " at Position";
       echo strpos($str,$substr,0). "\xA";}
      }

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