Counting the number of specific characters inside string

前端 未结 6 977
鱼传尺愫
鱼传尺愫 2020-12-31 18:44

I\'m sorry, I just found a new problem due to my question about: Get The Number of Sepecific String Inside String.

I have been trying hard, how to find the number of

6条回答
  •  迷失自我
    2020-12-31 18:52

    A possible solution using regular expression:

    function get_num_chars($char) {
        $string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
        return preg_match_all('/'.$char.'(?=,|$)/', $string, $m);
    }
    
    echo get_num_chars('M');    // 2
    echo get_num_chars('M-1');  // 1
    echo get_num_chars('M-2');  // 1
    echo get_num_chars('K');    // 1
    echo get_num_chars('K-1');  // 1
    

提交回复
热议问题