Anzahl der Vorkommen eines Wortes im String

Einklappen
X
 
  • Filter
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge

  • Anzahl der Vorkommen eines Wortes im String

    Hallo,


    Wie kann ich zählen, wie oft ein Wort im String vorkommt?


    PHP-Code:
    <?php

    function count_words($str) {
      
    $word_count = array();
      
    $array explode(" "$str);
      
      foreach(
    $array as $var) {
        
    $word_count[$var]++;
      }

      return 
    $word_count;
    }

    ?>
    So? Oder gibt es da auch noch ne andere Möglichkeit?


    Floriam


    EDIT:
    Sorry, zählt natürlich jedes Wort, aber wollte wissen ob der Ansatz richtig ist
    Zuletzt geändert von Floriam; 06.01.2004, 14:15.
    PHP Handbuch - MySQL Handbuch - PHP Einsteiger Tutorial - CSS Referenz - Browserunterstützung von CSS

  • #2
    PHP-Code:
    function do_count($where)
    {
      
    $where=preg_replace('%[^a-z0-9 ]%'''$where);
      return 
    array_count_values(explode(' 'strtolower($where)));

    so vielleicht, aber ohne garantie

    wenn du ein spezielles word suchst, hilft dir http://www.php.net/substr-count weiter
    Ich denke, also bin ich. - Einige sind trotzdem...

    Kommentar


    • #3
      PHP-Code:
      function word_count($word$string)
      {
      $a explode($word$string);
      return (
      count($a) - 1);

      is jetzt nur so ausm stegreif aber müsste funktionieren.
      edit:
      vorredner hat bessere möglichkeit gegeben: substr_count
      Just another bit of chaos engineered
      by dD

      Kommentar

      Lädt...
      X