Reputation: 992
I'm trying to use strlen
or something like that to count multiple set of characters
in a string.
Here's the database string
xa1xb2xcxd3xe4xcxa5xb6xcxd7xe8xcxa9xb10xcxd11xe12xcxa13xb14xc
I get the string from the database and i want to count the number of
"xa" "xb" "xd" and "xe" that the string contains.
I Guess i could count first xa then xb then xd then xe with strlen
and then adding the numbers but isn't there an easier way?
Please help!
Upvotes: 0
Views: 435
Reputation: 60594
Are you open to preg_match_all
solution?
echo preg_match_all('/x(a|b|d|e)/', $message, $matches)
From the docs:
Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.
Although this returns the aggregated number of xa,xb,xd and xe
, not the individual ones
If you need to get individual ones, you need one more step with array_count_values
:
$sums = array_count_values($matches[0]);
print_r($sums);
Upvotes: 2
Reputation: 1114
Try this one.
$string ="xa1xb2xcxd3xe4xcxa5xb6xcxd7xe8xcxa9xb10xcxd11xe12xcxa13xb14xc";
echo substr_count($string, 'xa')."<br>";
echo substr_count($string, 'xb')."<br>";
echo substr_count($string, 'xc')."<br>";
echo substr_count($string, 'xd')."<br>";
Upvotes: 1
Reputation: 60088
http://php.net/manual/en/function.substr-count.php
$text = "xa1xb2xcxd3xe4xcxa5xb6xcxd7xe8xcxa9xb10xcxd11xe12xcxa13xb14xc";
echo substr_count($text, 'xa');
echo substr_count($text, 'xb');
echo substr_count($text, 'xd');
Upvotes: 0