General Question

wenn's avatar

PHP echo number of instances if specific word?

Asked by wenn (2673points) November 1st, 2009

I have exploded an array and found the word “and” in it, and i want to echo the number of times it occurs.

anyone enlighten me to a simple solution?

——————

$content = “array that is exploded, its pretty long so i just used this for example text but should return 4 ‘and’s ”;

$and = “and”;
$words = explode(” ”, $content);

if (in_array($and, $words)) {
echo ”‘and’ occurs this many times”;
}
else {
echo “none”;
}

Observing members: 0 Composing members: 0

6 Answers

ragingloli's avatar

make a while loop that goes through the contents of the array. prior to the array define a counting variable and give it the value 0. during each loop, increase the value by 1 if the word “and” is encountered

ragingloli's avatar

you could also make a foreach-loop

$contents = array(‘and’, ‘and’, ‘and’, ‘and’, ‘lol’, ‘and’);

$x=0;

foreach ($contents as $word) {
if($word == “and”)
{
$x=$x+1;
}
}
echo $x;

phoenyx's avatar

I think a simpler approach would be to just scan over the string itself rather than exploding it into an array and manipulating the array. For example, strpos() to find the first “and”, use that as an offset in strpos() to find the second “and”, use that as an offset to find the third “and”, etc.

Or there’ s always: shell_exec(‘grep and foo.txt | wc -w’)
;)

wenn's avatar

@phoenyx its for a class so it needs to be done in a certain method, so im stuck exploding it.

but ive managed to get it to work. thanks for inputs

markyy's avatar

I’ll bet you get bonus points for adding @phoenyx’ solution, just hand in both solutions. You could also go for a regular expression, although I doubt that would be very efficient.

funkdaddy's avatar

PHP has a function called substr_count that’s specifically for this purpose

echo ‘and occurs ’ . substr_count($content, ’ and ’) . ’ times.’;

documentation here

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther