Counting the number of specific characters inside string

前端 未结 6 975
鱼传尺愫
鱼传尺愫 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
    
    0 讨论(0)
  • 2020-12-31 18:53
    $k_count = substr_count($string, 'K') - substr_count($string, 'K-');
    $k1_count = substr_count($string, 'K-1');
    

    or

    Counting K not followed by dash as follows:

    $k_count = preg_match_all('/*K(?!-)/*', $string, $out);
    
    0 讨论(0)
  • 2020-12-31 18:58

    Try this, it might not be feasible but addresses your problem

    function get_num_chars($char) {
    
        $string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
        echo substr_count($string, $char);
    }
    get_num_chars('M,');
    get_num_chars('M-1');
    get_num_chars('k,');
    
    0 讨论(0)
  • 2020-12-31 19:00

    Check this,

    $string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
    $arrString = explode($string,'M');
    echo $stringCount = count($arrString);
    
    0 讨论(0)
  • 2020-12-31 19:09

    It is possible with substr_count()

    I think you are not passing value in it properly try like this

    $string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
    
    echo substr_count($string, 'K-1');//echo's 1
    
    echo substr_count($string, 'K');// echo's 2
    
    0 讨论(0)
  • 2020-12-31 19:09

    Try this

     $string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
    
     $wordCounts = array_count_values(str_word_count($string,1));
    
     echo $mCount = (isset($wordCounts['M-'])) ? $wordCounts['M'] : 0;
    

    But here one thing You can just pass the 'M-' or 'M' not 'M-1' it is some workaround for what you want. Beacuse str_word_count matches exact word count been used.

    0 讨论(0)
提交回复
热议问题