settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Count String Occurrences - String Task

+6 votes

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

asked in PHP category by user Jolie Ann

1 Answer

+5 votes

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;
answered by user matthew44
...