str_word_count

str_word_count(string $string, int $format = 0, ?string $characters = null): array|int

Counts words in a string: a word is an alphanumeric run that may contain (but not start with) ' and -; format 0 returns the count, 1 the word array, 2 an offset-to-word map — the word-level counterpart of count_chars' byte-level histogram; single-byte implementation, multibyte text needs the regex route.

C C23

C23
#include <ctype.h>
#include <stdio.h>

/* no word counter in libc: one pass with PHP's rule - alnum runs,
   inner ' and - allowed */
static int count_words(const char *s) {
    int n = 0, in_word = 0;
    for (; *s != '\0'; s++) {
        int is_word_char = isalnum((unsigned char)*s) || *s == '\'' || *s == '-';
        if (is_word_char && !in_word) {
            n++;
            in_word = 1;
        } else if (!is_word_char) {
            in_word = 0;
        }
    }
    return n;
}

int main(void) {
    printf("%d\n", count_words("the quick brown fox jumps")); /* 5 */
    printf("%d\n", count_words("hello,world")); /* 2: comma splits */
    printf("%d\n", count_words("don't stop-me")); /* 2: ' and - stay inside */
    return 0;
}
Output
5
2
2

C++ C++26

C++26
#include <cctype>
#include <iostream>
#include <string>

// no std word counter: hand-written scanner with PHP's rule
static int count_words(const std::string &s) {
    int n = 0;
    bool in_word = false;
    for (char ch : s) {
        bool wc = std::isalnum(static_cast<unsigned char>(ch)) || ch == '\'' || ch == '-';
        if (wc && !in_word) {
            n++;
            in_word = true;
        } else if (!wc) {
            in_word = false;
        }
    }
    return n;
}

int main() {
    std::cout << count_words("the quick brown fox jumps") << "\n"; // 5
    std::cout << count_words("hello,world") << "\n"; // 2: comma splits
    std::cout << count_words("don't stop-me") << "\n"; // 2: ' and - stay inside
    return 0;
}
Output
5
2
2

C# v11.0.100

v11.0.100
using System;
using System.Text.RegularExpressions;

// no str_word_count in .NET either: Regex.Matches with PHP's word rule;
// the whitespace route (Split) is the Python split cousin
Console.WriteLine("the quick brown fox jumps".Split(' ', StringSplitOptions.RemoveEmptyEntries).Length); // 5
var word = new Regex(@"[A-Za-z]+(?:['-][A-Za-z]+)*");
Console.WriteLine(word.Matches("hello,world").Count); // 2 - the PHP rule
Console.WriteLine(word.Matches("don't stop-me").Count); // 2
Output
5
2
2

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"regexp"
	"strings"
)

// strings.Fields = the whitespace splitter (Python split cousin);
// a hand-written regexp reproduces PHP's word rule
func main() {
	fmt.Println(len(strings.Fields("the quick brown fox jumps"))) // 5
	fmt.Println(len(strings.Fields("hello,world")))               // 1 - whitespace only
	word := regexp.MustCompile(`[A-Za-z]+(?:['-][A-Za-z]+)*`)
	fmt.Println(len(word.FindAllString("hello,world", -1)))   // 2 - the PHP rule
	fmt.Println(len(word.FindAllString("don't stop-me", -1))) // 2
}
Output
5
1
2
2

Java v27.0.1

v27.0.1
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String s = "the quick brown fox jumps";
        System.out.println(s.split("\\s+").length); // 5 - whitespace route
        // PHP's word rule hand-written: alphanumeric runs with inner ' or -
        Pattern word = Pattern.compile("[A-Za-z]+(?:['-][A-Za-z]+)*");
        System.out.println(word.matcher("hello,world").results().count()); // 2
        System.out.println(word.matcher("don't stop-me").results().count()); // 2
    }
}
Output
5
2
2

JavaScript v26.13.1

v26.13.1
// no std word counter - PHP's rule hand-written with one regex;
// note the rule: alphanumeric runs may carry inner ' or - (but not start with them)
const words = (s) => s.match(/[A-Za-z]+(?:['-][A-Za-z]+)*/g) ?? [];
console.log(words("the quick brown fox jumps").length); // 5
console.log(words("hello,world").length); // 2 - the PHP rule, not split()
console.log(words("don't stop-me").length); // 2
Output
5
2
2

PHP v8.6.0

v8.6.0
// str_word_count(): words = alphanumeric runs that may contain (not start
// with) ' and -; locale-dependent, single-byte - the byte-level counterpart
// is count_chars (A41)
$s = "the quick brown fox jumps";
echo str_word_count($s), "\n"; // 5 - whitespace text: same as len(split())
echo str_word_count("hello,world"), "\n"; // 2: comma is no word char, PHP sees two words
echo str_word_count("don't stop-me"), "\n"; // 2: ' and - stay inside words
print_r(str_word_count($s, 1)); // format 1: the word list
echo preg_match_all('/\p{L}+/u', "caf\u{e9} au lait"), "\n"; // 3 - multibyte needs the regex route
Output
5
2
2
Array
(
    [0] => the
    [1] => quick
    [2] => brown
    [3] => fox
    [4] => jumps
)
3

Python v3.15.2

v3.15.2
import re

# len(split()): Python's word count is whitespace-based - the punctuation
# rule differs from PHP; regex brings it in line when needed
s = "the quick brown fox jumps"
print(len(s.split()))                 # 5
print(len("hello,world".split()))     # 1 - Python keeps "hello,world" as ONE token
print(len("don't stop-me".split()))   # 2
print(len(re.findall(r"[^\W\d_]+", "caf\u00e9 au lait")))  # 3 - Unicode letters only
Output
5
1
2
3

Rust v1.99.1

v1.99.1
// std has no word counter: split_whitespace is the Python-split cousin;
// the PHP word rule is one filter away - alphanumeric + inner ' or -
fn count_words(s: &str) -> usize {
    s.split(|c: char| !(c.is_alphanumeric() || c == '\'' || c == '-'))
        .filter(|w| !w.is_empty())
        .count()
}

fn main() {
    println!("{}", "the quick brown fox jumps".split_whitespace().count()); // 5
    println!("{}", count_words("hello,world")); // 2 - the PHP rule
    println!("{}", count_words("don't stop-me")); // 2
}
Output
5
2
2

TypeScript v26.13.1

v26.13.1
// no std word counter - PHP's rule hand-written with one regex;
// note the rule: alphanumeric runs may carry inner ' or - (but not start with them)
const words = (s: string): string[] => s.match(/[A-Za-z]+(?:['-][A-Za-z]+)*/g) ?? [];
console.log(words("the quick brown fox jumps").length); // 5
console.log(words("hello,world").length); // 2 - the PHP rule, not split()
console.log(words("don't stop-me").length); // 2
Output
5
2
2

Language differences

Word-level vs byte-level: count_chars (A41) answers "how often does each byte occur", this entry answers "how many words" — complementary granularities; the deterministic assertions: the fixed sentence "the quick brown fox jumps" is always 5 words, "hello,world" always 2 (the comma splits words), "don't stop-me" always 2 (' and - stay inside) — fixed inputs independent of locale.

PHP: str_word_count($s, $format, $characters) — format 0 = count, 1 = word array, 2 = offset-to-word map; $characters adds word chars (e.g. digits); caution: the word definition is locale-dependent (setlocale can widen beyond a-z) and multibyte is unsupported — use preg_split('/\p{L}+/u', ...) for CJK/accented text; a format outside 0/1/2 throws ValueError (since 8.0).

Python: len(s.split()) is the whitespace-splitting rule — "hello,world" counts as 1 token (PHP says 2); the gap between the two rules is exactly "does punctuation split words"; the Unicode word rule is re.findall(r"[^\W\d_]+", ...) (\w minus digits and underscore).

Go: strings.Fields follows the Python split rule; the PHP word rule is reproduced with regexp.MustCompile("[A-Za-z]+(?:['-][A-Za-z]+)*").

Java: split("\\s+") is the whitespace rule; the PHP rule uses Pattern plus Matcher.results().count() (stream counting, Java 9+).

C#: Regex.Matches(...).Count is the shortest reproduction of the word rule; Split(' ', RemoveEmptyEntries) is the whitespace rule.

JavaScript/TypeScript: String.match with a global regex is the handwritten form; ?? [] guards the null-on-no-match trap.

C/C++: libc/libstdc++ have no word counter — a single-pass state machine (in_word flip) IS the str_word_count implementation principle; isalnum is locale-sensitive (C locale means exactly a-zA-Z0-9).

Rust: split_whitespace is the whitespace rule; split(predicate) plus filter(non-empty) reproduces the PHP word rule in one step, and char::is_alphanumeric is Unicode-aware.