skip to Main Content

I have created a function that converts emoji short name to image but I am stuck how do i get emojis short names from a string so the function can convert those to emoji image .

$field_from_db  = ':slight_smile:';
$shortcode_replace = shortcode_replace();
$shortname = $shortcode_replace[$field_from_db]; This code search in shortcode fucntion and replaces it with unicode to get cdn image 
$shortname = $shortname[0];


echo convertImage($shortname); after we got unicode for cdn predesigned in the shortcodes function it returns back with the image url 

Now i am confuse how it will convert from a string

$field_from_db  = 'Hello How are you :slight_smile::joy:';
//Here we have a string so how do i convert all short names to emoji using the function i created 

2

Answers


  1. A simple solution is to use preg_match_all function to return the short names from string and iterate through each of them to convert into image.

    <?php
    
    $string  = 'Hello How are you :slight_smile::joy:';
    
    $regex = "/:([a-zA-Z0-9_]*):/";
    preg_match_all($regex, $string, $matches);
    
    print_r($matches[0]);
    

    Demo: https://3v4l.org/ro1m3

    Hope it helps!

    Login or Signup to reply.
  2. Depending on the format of the short names that you store, you could for example start the match with 1 or more a characters a-z or digits using a case insensitive pattern.

    Then optionally repeat a single character from for examople a character class [-’_] followed by again 1 or more a characters a-z or digits.

    :[a-z0-9]+(?:[-’_][a-z0-9]+)*:
    

    Regex demo | Php demo

    For a bit broader match, you could match 1 or more non whitespace characters excluding a colon, between to colons:

    :[^:s]+:
    

    Regex demo

    Example:

    $field_from_db  = 'Hello How are you :slight_smile::joy::_do_not_match:test test::';
    $regex = '/:[a-z0-9]+(?:[-’_][a-z0-9]+)*:/i';
    preg_match_all($regex, $field_from_db, $matches);
    var_export($matches[0]);
    

    Output

    array (
      0 => ':slight_smile:',
      1 => ':joy:',
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search