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

4

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

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

I can see if there is a certain word within the sentence using strpos , like this:

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

How can I check how many times the word "what" is repeated in this sentence?

    
asked by anonymous 26.01.2017 / 18:00

2 answers

8

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

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:

$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 captures do: print_r($ocorrencias);

Related:

What is a boundary \ b in a regular expression?

    
26.01.2017 / 18:07
8

PHP already has 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 at IDEONE .

If you do not want to count the que of the word quer , just fill in the spaces:

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

In case:

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

See working at IDEONE .

If you do not want to make a difference:

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

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

More details in the manual:

  

link

    
26.01.2017 / 18:05