What are some alternative methods to using explode and substr_count in PHP for counting occurrences of elements in a string?

When counting occurrences of elements in a string, instead of using explode and substr_count, we can use regular expressions or iterate through the string character by character. Regular expressions provide a powerful way to match patterns in strings, while iterating through the string allows for more control over the counting process.

// Using regular expressions to count occurrences of elements in a string
$string = "hello world hello";
$pattern = '/hello/';
$count = preg_match_all($pattern, $string);
echo $count;

// Iterating through the string to count occurrences of elements
$string = "hello world hello";
$target = "hello";
$count = 0;
for($i = 0; $i < strlen($string); $i++) {
    if(substr($string, $i, strlen($target)) === $target) {
        $count++;
    }
}
echo $count;