Page 1 of 1

number of occurances of a symbol in string?

Posted: Tue Oct 24, 2006 7:20 am
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.

Posted: Tue Oct 24, 2006 7:30 am
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";

Posted: Tue Oct 24, 2006 7:43 am
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;

Posted: Tue Oct 24, 2006 7:55 am
by impulse()
Has that just speeded up the process?

Posted: Tue Oct 24, 2006 7:59 am
by printf
substr_count();

Code: Select all

<?php

$str = 'dslkjf skj3 kdkjj';

echo substr_count ( $str, 'd' );

?>
pif!

Posted: Tue Oct 24, 2006 8:15 am
by jmut
printf wrote:substr_count();

Code: Select all

<?php

$str = 'dslkjf skj3 kdkjj';

echo substr_count ( $str, 'd' );

?>
pif!
8O solid. respect.