tags:

views:

413

answers:

4

the most efficient way?

A: 

Can you not feed the character to preg_match_all?

CodeToGlory
It's not efficient to use a regex just to look for one static character.
Etienne Perot
+3  A: 

use this:

echo substr_count("abca", "a"); // will echo 2
Ozzy
A: 

Not sure what kind of a response you're looking for, but here's a function that might do it:

function findChar($c, $str) {
    indexes = array();
    for($i=0; $i<strlen($str); $i++) {
        if ($str{$i}==$c) $indexes[] = $i;
    }
    return $indexes;
}

Pass it the character you're looking for and the string you want to look:

$mystring = "She shells out C# code on the sea shore";
$mychar = "s";
$myindexes = $findChar($mychar, $mystring);
print_r($myindexes);

It should give you something like

Array (
    [0] => 0
    [1] => 4
    [2] => 9
    [3] => 31
    [4] => 35
)

or something...

aalaap
A: 

If you are going to be repeatedly checking the same string, it'd be smart to have some sort of trie or even assoc array for it otherwise, the straightforward way to do it is...

for($i = 0; $i < strlen($s); $i++)
  if($s[i] == $c)
    echo "{$s[i]} at position $i";
nategood