代码之家  ›  专栏  ›  技术社区  ›  GM.

如何在字符串中查找字符的出现次数

php
  •  1
  • GM.  · 技术社区  · 16 年前

    输入这些参数“hello world”,o将返回2

    3 回复  |  直到 16 年前
        1
  •  8
  •   RageZ    16 年前

    substr_count 他是你的朋友吗

    var_dump( substr_count("hello world", 'o') );
    

    笔记 这也会起作用 子计数器 搜索子字符串

    var_dump( substr_count("hello world", 'hello') );
    
        2
  •  1
  •   RageZ    16 年前

    strlen() 在字符串和 str_replace() 使用所需的字符。然后你得到了 斯特伦() 对于被截断的字符串,lens之间的差异是char count=)

    function count_char_occurence($haystack,$needle){
       $len = strlen($haystack);
       $len2 = strlen(str_replace($needle, '', $haystack));
       return $len - $len2;
    }
    

    用speudo算法

    print len("hello world")  : You get 11
    
    a = replace("","o","hello world") : You get "hell wrld"
    
    print len(a) : You get a 9
    

    然后11-9=2。这是你的字符数。

        3
  •  0
  •   Darren user513543    14 年前

    <form action="" method=post>
    Give ur String: <input type="text" name="str" value="<? echo $_POST["str"]; ?>"/>
    Search What Char: <input type="text" name="x" value="<? echo $_POST["x"]; ?>"/>
    
    <input value="submit" name="submit" type="submit"/>
    </form>
    
    <?php
    if (isset($_POST['submit']))
    {
    echo substr_count($_POST["str"], $_POST['x'] );
    }
    ?> 
    
    推荐文章