How do you count the number of times a word repeats itself in a sentence?

Asked

Viewed 1,746 times

5

I have a certain phrase declared in a variable. See:

$bacco = "Você tem que abrir seu coração pro SQL e pedir o que realmente quer."; 

I can verify if there is a certain word inside the sentence using strpos, in this way:

if (strpos($bacco, 'que') !== false) {
    echo 'true';
} 

How can I check the number of times the word "that" repeats in this sentence?

2 answers

9

PHP already has a function ready for this:

$ack = "Você tem que abrir seu coração pro SQL e pedir o que realmente quer."; 
echo substr_count ( $ack, 'que' );

See working on IDEONE.

If you don’t want to tell que of the word quer, is enough for spaces:

echo substr_count( ' '.$frase.' ', ' '.$palavra.' ' );

In the case:

echo substr_count( ' '.$ack.' ', ' que ' );

See working on IDEONE.

If you want upper and lower case to make no difference:

echo substr_count( mb_strtoupper($ack), mb_strtoupper('que') );

Of course, in this case, you can use the space technique as well.

More details in the manual:

http://php.net/manual/en/function.substr-count.php

  • 5

    I can barely see your movements

8


You can use a regex to search for the exact word using the search term enter the anchor \b to function preg_match_all() returns the number of occurrences captured, in case two once quer or qualquer shall not be counted.

If you need to manipulate the captured elements enter the third argument in the function call:

$str = "Você tem que abrir seu coração pro SQL e pedir o que realmente quer qualque."; 
$contagem = preg_match_all('/\bque\b/i', $str);
echo $contagem;

Or else:

$str = "Você tem que abrir seu coração pro SQL e pedir o que realmente quer qualque."; 
preg_match_all('/\bque\b/i', $str, $ocorrencias);
echo count($ocorrencias[0]);

If you want to see all the catches do: print_r($ocorrencias);

Related:

What good is a b oundary in a regular expression?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.