The substr_count Function

The substr_count function counts how many times a substring occurs in a string. Works correctly only with Latin characters (single-byte characters).

Syntax

phpsubstr_count(string $haystack, string $needle, int $offset = 0, ?int $length = null): int

Example

Let's count how many times the substring 'test' appears in our string:

php<?php
  echo substr_count('test www test', 'test');  
?>

Code execution result:

php2

See Also

  • the mb_substr_count function,
    which works with multibyte encodings
  • the str_word_count function,
    which counts the number of words in a string
  • the substr_count function,
    which counts the number of substrings
  • the count_chars function,
    which counts the number of characters