0

I am working with emojis, and I have a JSON file which maps the colon code for each emoji to it's Unicode char. A piece of the file:

{":grinning:":"",
":grimacing:":"",
":grin:":"",
":joy:":"",
":smiley:":""}
.... it has more than 1200 elements

I got this file in PHP, decode it, and I am looking for the pattern :***: in my message string, so I can replace this unicode word for the real emoji.

The thing is: I find and get the pattern, look for it in the Emoji array and it gives me "Undefined index" error.

array_key() returns true for the pattern.

This is my PHP code:

$message = $row['body'];
preg_match('/:(.*?):/', $row['body'], $matches, PREG_OFFSET_CAPTURE);

if (isset($matches[0])) {

    //get Emoji map
    $stringMap = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/v1/emoji-map.json");
    $jsonMap = json_decode($stringMap, true);

    foreach ($matches as $key => $value) {
        $emojiColon = $value[0];

        print key_exists($emojiColon, $jsonMap); // returns true

        print ($emojiColon); // prints the founded pattern (ie. :smiley:)

        $emoji = $jsonMap[$value[0]]; // this line returns the ERROR "Undefined Index"

        print $emoji; // returns the EMOJI!!! WTF

        $message = str_replace($emojiColon, $emoji, $message);

    }
}

The error returned by this snippet is:

1:smiley:
<html>
<head><title>Slim Application Error</title>
</head>
<body><h1>Slim Application Error</h1>
<p>The application could not run because of the following error:</p>
<h2>Details</h2>
<div><strong>Code:</strong> 8</div>
<div><strong>Message:</strong> Undefined offset: 0</div>
<div><strong>File:</strong> /var/www/apid.inngage.com.br/v1/DBFunctions.php</div>
<div><strong>Line:</strong> 123</div>
<h2>Trace</h2>
<pre>#0 /var/www/apid.inngage.com.br/v1/DBFunctions.php(123): Slim::handleErrors(8, 'Undefined offse...', '/var/www/apid.i...', 123, Array)

Why is it returning this error if the index is set and the emoji is even returned after all?

jpenna
  • 8,426
  • 5
  • 28
  • 36
  • 1
    Use `$emoji = $jsonMap[$value]` The foreach returns a single value, therefore index is not required – RiggsFolly Nov 25 '16 at 01:14
  • 1
    Did you perhaps switch between `preg_match()` and `preg_match_all()` during your tests? You should go for preg_match_all here. – Johnny Nov 25 '16 at 01:18
  • @Johnny, I was doing the simplest first, now it's `preg_match_all()` =) – jpenna Nov 25 '16 at 01:41
  • @RiggsFolly, that question gave me a light, thanks! I have to use the `$emoji = $jsonMap[$value]` because it gives me 2 values: one including all the pattern and other with the bare match. And turns out that this was the problem!! The first loop was looking for the right pattern (`:smiley:`), but there was a second loop going on, which was catching the second element of the array `smiley` and messing all. I am still using the index, but now the right way – jpenna Nov 25 '16 at 01:42

0 Answers0