Forum Moderators: coopster

Message Too Old, No Replies

Counting characters

Bit of a newbie question =\

         

xeonaphobe

1:53 am on Feb 20, 2005 (gmt 0)

10+ Year Member



Hi there,

Just a silly little problem i'm not entirely sure how to tackle. I'm wanting to search through a string for a certain character and then count the number of times it appears (or return false if it doesn't locate the character).

All suggestions greatly appreciated =)

Neil

badone

3:11 am on Feb 20, 2005 (gmt 0)

10+ Year Member



[php.net...]

IanKelley

10:10 am on Feb 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Regular expressions will work, but if it's a situation where the code could end up in a high traffic application you might want to use strpos() instead:
[php.net ]

hakre

6:02 pm on Feb 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



my favour: keep the solution as simple as possible. regular expressions using for this task in php is like buying a complete toolbox and the using the screwdriver only. strpos is a nice alternative to regex, but only in specific cases and this is written as a warning in the php docs, too and it will only tell you the position of one character/string within another and not more.

to have this solved by php, just use the function designed for it: substr_count() [php.net]:

substr_count("hello world","l")
will return 3, because "l" exists 3 times in "hello world". i think that is what you asked for.

xeonaphobe

7:10 pm on Feb 20, 2005 (gmt 0)

10+ Year Member



ah yes, substr_count() looks like the way to go!

Many thanks :)
Neil