【问题标题】:PHP count amount of letters in a substring matchPHP计算子字符串匹配中的字母数量
【发布时间】:2020-03-12 16:38:26
【问题描述】:

我有一个字符串和三个子字符串:

$str = "smartphones";

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

通过函数运行三个子字符串应该分别返回 5、4 和 10。如果没有匹配,它应该返回 0。

编辑:

另外,如果字符串是“智能手机和其他手机”,$substr2 仍应返回 4,而不是 8

【问题讨论】:

标签: php


【解决方案1】:
$str = "smartphones";

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

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

【讨论】:

    【解决方案2】:

    您可以使用strpos() 函数查找第一次出现的子字符串,然后只返回子字符串的长度。

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

    【讨论】:

      【解决方案3】:

      好吧,鉴于上面的答案并不是你想要的:) 我会这样解决它:

          //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";}
            }
      

      【讨论】:

        猜你喜欢
        • 2014-04-20
        • 1970-01-01
        • 2023-03-19
        • 2014-07-08
        • 1970-01-01
        • 2017-10-20
        • 1970-01-01
        • 2012-10-18
        • 1970-01-01
        相关资源
        最近更新 更多