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
jmut
Forum Regular
Posts: 945 Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:
Post
by jmut » Tue Oct 24, 2006 7:20 am
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() » Tue Oct 24, 2006 7:30 am
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";
jayshields
DevNet Resident
Posts: 1912 Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England
Post
by jayshields » Tue Oct 24, 2006 7:43 am
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() » Tue Oct 24, 2006 7:55 am
Has that just speeded up the process?
printf
Forum Contributor
Posts: 173 Joined: Wed Jan 12, 2005 5:24 pm
Post
by printf » Tue Oct 24, 2006 7:59 am
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 » Tue Oct 24, 2006 8:15 am
printf wrote: substr_count();
Code: Select all
<?php
$str = 'dslkjf skj3 kdkjj';
echo substr_count ( $str, 'd' );
?>
pif!
solid. respect.