number of occurances of a symbol in string?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

number of occurances of a symbol in string?

Post by jmut »

Hi,
How can I find out how many times "d" is within "dslkjf skj3 kdkjj" ? :) -> answer will be 2
I know how to do this with preg_match_all ...but is kind of overload.
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Post by impulse() »

You could do:

Code: Select all

$string = "Your string goes here";

for ($i = 0; $i < count($string); $i++) {
  if ($string[$i] == "d") {
    $count += 1;
  }
}

echo "D appeared $count times";
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

impulse() wrote:You could do:

Code: Select all

$string = 'Your string goes here';
$char = 'd';

$strlen = count($string);
$count = 0;
for ($i = 0; $i < $strlen; $i++) {
  if ($string[$i] == $char) {
    $count += 1;
  }
}

echo $char . ' appeared ' . $count . ' time(s) in ' . $string;
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Post by impulse() »

Has that just speeded up the process?
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post by printf »

substr_count();

Code: Select all

<?php

$str = 'dslkjf skj3 kdkjj';

echo substr_count ( $str, 'd' );

?>
pif!
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post by jmut »

printf wrote:substr_count();

Code: Select all

<?php

$str = 'dslkjf skj3 kdkjj';

echo substr_count ( $str, 'd' );

?>
pif!
8O solid. respect.
Post Reply