|
Posted by My Pet Programmer on 12/28/07 14:13
jodleren said:
> Hi!
>
> I was reading php.net for a way to find a number of characters in a
> strings. Say I want to look for a b and c ind $string.
> As far as I could see, there is no function for that.
>
> So, I can either?
> 1) run through the string and test using in_array('a', 'b', 'c')
> 2) run through array and test using strpos( $items[$i]....
> Where I find #2 the best.
>
> But is there a function which can do that faster or in a better way?
So you have one string, and you want to see if each of your elements are
in it individually.
So:
$needles = array("a", "b", "c");
$haystack = "This is a string with a certain number of each character in
it.";
$counts = array();
function countChars($letter, $key, $arr) {
global $output;
$garbage = explode($letter, $arr[0]);
$arr[1][$letter] = count($garbage)-1;
}
array_walk($needles, 'countChars', array($haystack, &$counts));
print_r($counts); // Array ( [a] => 6 [b] => 1 [c] => 4 )
That's a little cleaner, I suppose. You're still going through a bunch,
but if you're just counting, that will return an array that looks like that.
All the best,
~A!
--
Anthony Levensalor
anthony@mypetprogrammer.com
Only two things are infinite, the universe and human stupidity,
and I'm not sure about the former. - Albert Einstein
[Back to original message]
|