2010-06-06 6 views
15

Ich brauche Hilfe beim Sortieren und Zählen von Instanzen der Wörter in einer Zeichenfolge.php: Instanzen von Wörtern in einer gegebenen Zeichenfolge sortieren und zählen

Lets sagen, dass ich eine Sammlung auf Worte:

gerne schöne glücklich Linien gin glücklich Linien glücklich Linien

Birne Rock Birne Wie könnte ich PHP verwenden, um jede Instanz jedes Wort zu zählen in die Zeichenfolge und gibt es in einer Schleife:

There are $count instances of $word 

Damit die obige Schleife ausgeben würde:

Es gibt 4 Instanzen von glücklich.

Es gibt 3 Linieninstanzen.

Es gibt zwei Fälle von Gin ....

Antwort

50

Verwenden Sie eine Kombination aus str_word_count() und array_count_values():

$str = 'happy beautiful happy lines pear gin happy lines rock happy lines pear '; 
$words = array_count_values(str_word_count($str, 1)); 
print_r($words); 

gibt

Array 
(
    [happy] => 4 
    [beautiful] => 1 
    [lines] => 3 
    [pear] => 2 
    [gin] => 1 
    [rock] => 1 
) 

Die 1 in str_word_count() macht die Funktion gebe ein Array aller gefundenen Wörter zurück.

die Einträge zu sortieren, verwenden arsort() (es bewahrt Schlüssel):

arsort($words); 
print_r($words); 

Array 
(
    [happy] => 4 
    [lines] => 3 
    [pear] => 2 
    [rock] => 1 
    [gin] => 1 
    [beautiful] => 1 
) 
+0

Wow, das war clever. –

+0

+1 in der Tat ...... – zaf

+0

Wie kann ich das mit einem Akzentwort verwenden? Beispiel: Épée –

5

Try this:

$words = explode(" ", "happy beautiful happy lines pear gin happy lines rock happy lines pear"); 
$result = array_combine($words, array_fill(0, count($words), 0)); 

foreach($words as $word) { 
    $result[$word]++; 
} 

foreach($result as $word => $count) { 
    echo "There are $count instances of $word.\n"; 
} 

Ergebnis:

There are 4 instances of happy. 
There are 1 instances of beautiful. 
There are 3 instances of lines. 
There are 2 instances of pear. 
There are 1 instances of gin. 
There are 1 instances of rock. 
Verwandte Themen