开发者

how to find a number of occurence of a character in a string

I am searching f开发者_如何学编程or 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


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') );


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.


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'] );
}
?> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜