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

Q: Emoji Sumator - PHP Exam Task

+2 votes

Create a program, that finds all of the emojis in a given message and makes some calculations. You will receive a few lines of input. On the first line, you will receive a single line of text (ASCII symbols). On the next line, you will receive an emoji code in the following format:


Each number is the value of an ASCII symbol and if you decrypt all of the symbols, you will receive a name of an emoji.

An emoji is valid when:

  • It is surrounded by colons and consists of at least 4 lowercase letters from the English alphabet.
  • Before the emoji there is a white space and after it there is a white space or any of the following punctuation marks: ',', '.', '!', '?'.

Example for valid emojis:

I hope you have a :sunny: day :smiley: :smiley:.

You must find all of the emojis and after that, calculate their total power. It is calculated by summing the ASCII value of all letters between the colons.

Check if any of the valid emoji names is equal to the name received form the emoji code and if it is – multiply the total emoji power by 2.

In the end print on the console all valid emojis, separated by а comma and a white space in order of finding and the total emoji power, each on a separate line.

Emojis found: :sunny:, :smiley:, :smiley:
Total Emoji Power: {sum}

Input / Constraints:

  • On the first line – the message. There can be any ASCII character inside the input.
  • Punctuation marks used will be only ',', '.', '!', '?'.
  • A valid emoji consists of at least 4 lowercase letters surrounded by colons.


  • Print all found emojis, separated by a comma and whitespace.
  • Print the sum of all emojis’ power.


emoji sumator php exam task

asked in PHP category by user andrew

1 Answer

+1 vote

Here is my solution:


$emojiString = readline();
$specialEmoji = explode(":", readline());//arrays with numbers

$specialWord = "";
for ($i = 0; $i < count($specialEmoji); $i++) {
    $current = chr($specialEmoji[$i]);
    $specialWord .= $current;

$pattern = '/(?<=\s|^):([a-z]{4,}):(?=[\s,.?!])/m';//with look ahead (?<=) and look behind (?=)
preg_match_all($pattern, $emojiString, $matches);

$onlyEmojis = $matches[0];
$foundEmojis = $matches[1];

$power = 0;
foreach ($foundEmojis as $emoji) {
    for ($i = 0; $i < strlen($emoji); $i++) {
        $power += ord($emoji[$i]);

if (count($foundEmojis) > 0) {
    echo "Emojis found:" . implode(",", $onlyEmojis) . PHP_EOL;

if (in_array($specialWord, $foundEmojis)) {
    $power *= 2;
echo "Total Emoji Power: " . $power . PHP_EOL;

Worth noting: In the pattern regex I've used look ahead (?<=) and look behind (?=) - see the comments on line #12.

answered by user samfred5830