tags:

views:

108

answers:

3

I am searching for a function in PHP to return the number of occurence of a character in a string.

Inputing those parameters "hello world", 'o' would return 2

+8  A: 

substr_count is your friend

var_dump( substr_count("hello world", 'o') );

note: this would also work since substr_count search for sub string

var_dump( substr_count("hello world", 'hello') );
RageZ
LOL... I guess a short question deserves a short answer. :)
Doug Neiner
I suppose! just afraid if it's a homework but anyway that's not really like I have made a lot!
RageZ
+1 for the right answer. And an imaginary +1 for answering even though you thought it was homework :)
Doug Neiner
how to use HTML textbox value dynamically..
GM
usually homework are more C/C++/Java but never too careful.
RageZ
@murugan: your textbox is inside a `<form>` if the `method` is get `$_GET['yourtextboxname']`, if the method is post `$_POST['yourtextboxname']`
RageZ
+1  A: 

You can do a strlen() of the string and the, a str_replace() with the desired char. Then you get the strlen() of that truncated string, the difference between lens is the char count =)

Something like this:

function count_char_occurence($haystack,$needle){
   $len = strlen($haystack);
   $len2 = strlen(str_replace($needle, '', $haystack));
   return $len - $len2;
}

with that speudo algorithm

print len("hello world")  : You get 11

a = replace("","o","hello world") : You get "hell wrld"

print len(a) : You get a 9

Then 11 - 9 = 2. That is your char count.

mRt
A: 

including it in a form would give this:

<form action="" method=post>
Give ur String: <input type="text" name="str" value="<? echo $_POST["str"]; ?>"/>
Search What Char: <input type="text" name="x" value="<? echo $_POST["x"]; ?>"/>

<input value="submit" name="submit" type="submit"/>
</form>

<?php
if (isset($_POST['submit']))
{
echo substr_count($_POST["str"], $_POST['x'] );
}
?>
GM