Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of specific characters inside string

Tags:

string

php

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 specific character inside a string? The case something like this.

function get_num_chars($char) {
    $string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1'
}

If I pass get_num_chars(M) would return 2 If I pass get_num_chars(M-1) would return 1

I tried count_chars(), substr_count() but it doesn't work.

like image 230
Philips Tel Avatar asked Apr 23 '13 06:04

Philips Tel


2 Answers

It is possible with substr_count().

I think you are not passing a value to it properly. Try it 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
like image 78
chandresh_cool Avatar answered Oct 21 '22 16:10

chandresh_cool


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
like image 22
Randle392 Avatar answered Oct 21 '22 18:10

Randle392