"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Write a Basic Function in PHP to Remove Emojis from Text?

How to Write a Basic Function in PHP to Remove Emojis from Text?

Published on 2024-11-07
Browse:614

How to Write a Basic Function in PHP to Remove Emojis from Text?

Writing a Simple removeEmoji Function in PHP

Processing online text often requires the removal of emojis, particularly in cases like Instagram comments. This article explores a solution for such a need, utilizing the PHP preg_replace function to effectively eliminate emojis from a given text.

The removeEmoji function utilizes a series of regular expressions to match and remove emojis from the input text. Each expression targets specific unicode ranges that represent various categories of emojis, including emoticons, symbols, transport symbols, dingbats, and more.

Here's an example of the function:

public static function removeEmoji($text) {
    $clean_text = "";

    // Match Emoticons
    $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $clean_text = preg_replace($regexEmoticons, '', $text);

    // Match Miscellaneous Symbols and Pictographs
    $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $clean_text = preg_replace($regexSymbols, '', $clean_text);

    // Match Transport And Map Symbols
    $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
    $clean_text = preg_replace($regexTransport, '', $clean_text);

    // Match Miscellaneous Symbols
    $regexMisc = '/[\x{2600}-\x{26FF}]/u';
    $clean_text = preg_replace($regexMisc, '', $clean_text);

    // Match Dingbats
    $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
    $clean_text = preg_replace($regexDingbats, '', $clean_text);

    return $clean_text;
}

Note that this function does not exhaustively remove all emojis, as there are numerous variations. However, it provides a comprehensive solution for most common cases.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3