How to count words in a string with punctuation in PHP

1 Answer

0 votes
$s = 'python! ,,c, c++. c# $$$java@# php.';

// Define punctuation characters to strip
$punctuation = '!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';

// Split the string by whitespace
$words = explode(' ', $s);

$result = 0;

foreach ($words as $word) {
    // Remove punctuation from both ends
    $clean = trim($word, $punctuation);

    // Check if the cleaned word is alphabetic
    if (ctype_alpha($clean)) {
        $result++;
    }
}

echo $result;

  
  
/*
run:
    
6
    
*/

 



answered Nov 2, 2025 by avibootz
...