Skip to content
Advertisement

Extract specific data from string using Regex (PHP)

My objective is to check if the message have emojis or not , if yes i am going to convert them. I am having a problem to find out how many emojis are in the string.

Example :

$string = ":+1::+1::+1:"; //can be any string that has :something: between ::
  • the objective here is to get the :+1: ( all of them ) but i tried two pattern and i keep getting only 1 match.

    preg_match_all('/:(.*?):/', $string, $emojis, PREG_SET_ORDER); // $emojis is declared as $emojis='' at the beginning.
    preg_match_all('/:(S+):/', $string, $emojis, PREG_SET_ORDER);
    

The Rest of the code
after getting the matches i am doing this :

 if (isset($emojis[0])) 
   {
        $stringMap = file_get_contents("/api/common/emoji-map.json");
        $jsonMap = json_decode($stringMap, true);

        foreach ($emojis as $key => $value) {
            $emojiColon = $value[0];
            $emoji = key_exists($emojiColon, $jsonMap) ? $jsonMap[$emojiColon] : '';
            $newBody = str_replace($emojiColon, $emoji, $newBody);
        }
   }

i would appreciate any help or suggestions , Thanks.

Advertisement

Answer

I updated your expression a little bit:

preg_match_all('/:(.+?)(:)/', $string, $emojis, PREG_SET_ORDER);
echo var_dump($emojis);    
  • The : is now escaped, otherwise it could be treated as special character.
  • Replaced the * by +, this way you won’t match two consecutive :: but require at least one charcter in-between.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement