Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,954 questions

51,896 answers

573 users

How to count the occurrences of each word in a string with PHP

1 Answer

0 votes
function countWordOccurrences($string) {
    // Convert the string to lowercase to ensure case-insensitive counting
    $string = strtolower($string);
    
    // Remove punctuation and special characters
    $string = preg_replace('/[^\w\s]/', '', $string);
    
    // Split the string into an array of words
    $words = explode(' ', $string);
    
    // Count the occurrences of each word
    $wordCount = array_count_values($words);
    
    return $wordCount;
}

$string = "PHP is a general-purpose scripting language geared " . 
          "towards web development.[8] It was originally " .
          "created by Danish-Canadian programmer " . 
          "Rasmus Lerdorf in 1993 and released in 1995" . 
          "The PHP Group now produces the PHP reference implementation";

$result = countWordOccurrences($string);

print_r($result);



/*
run:

Array
(
    [php] => 3
    [is] => 1
    [a] => 1
    [generalpurpose] => 1
    [scripting] => 1
    [language] => 1
    [geared] => 1
    [towards] => 1
    [web] => 1
    [development8] => 1
    [it] => 1
    [was] => 1
    [originally] => 1
    [created] => 1
    [by] => 1
    [danishcanadian] => 1
    [programmer] => 1
    [rasmus] => 1
    [lerdorf] => 1
    [in] => 2
    [1993] => 1
    [and] => 1
    [released] => 1
    [1995the] => 1
    [group] => 1
    [now] => 1
    [produces] => 1
    [the] => 1
    [reference] => 1
    [implementation] => 1
)

*/

 



answered Mar 1, 2025 by avibootz

Related questions

1 answer 174 views
1 answer 116 views
1 answer 98 views
1 answer 88 views
1 answer 93 views
...