Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to count a particular word appearing in a text? 1

Status
Not open for further replies.

aas1611

Programmer
Dec 14, 2001
184
DE
Hi,

Let's say I have the following string/text:

$text= "new day new problem.";

How can I count the word "new", how many time it appears? (In this case, it appears 2 times).

It could also be two words, like "new day". In this case it appears once.

Please remember, that $text consists of several paragraphs.


Thanks!

Andre
 
Have you tried the [blue]substr_count()[/blue] The PHP online manual at php.net says this about it:
PHP Manual said:
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.

example:
Code:
$text = 'This is a test';
echo substr_count($text, 'is'); // 2

it finds the substring "is" 2 times in the original string.


----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Great, it works...!

However, how would it be, if a case insensitive was necessary?


Andre
 
using the same function (and this is ugly) and borrowing vacunita's post you could do

Code:
$text = 'This is a test';
echo substr_count(strtoupper($text), strtoupper('is')); // 2
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top