[Solved] Count String Occurrences - String Task

  

2
Topic starter

Write a program that receives a text and a string to search for. Use spaces, commas, dots, question marks and exclamation marks as word delimiters. Print all the occurrences of that word in the string

Examples:

count string occurrences php string task

1 Answer
2

You can use str_replace function in PHP and add the elements to be replaced as an array. Otherwise you can use, of course, Regex (regular expression).

My solution:

<?php
 
$string = readline();
$search = readline();
$count = 0;
 
$string = str_replace([" ", ",", ".", "?", "!"], "@", $string);
 
$arr = explode("@", $string);
foreach ($arr as $item) {
    if ($item == $search) {
        $count++;
    }
}
 
echo $count;
Share: