PHP Function To Strip Emojis From A String

/**
 * Strip any emoji icons from the string.
 *
 * @param string $string
 *   The string to remove emojis from.
 *
 * @return string
 *   The string with emojis removed.
 */
function stripEmojis($string) {
  // Convert question marks to a special thing so that we can remove
  // question marks later without any problems.
  $string = str_replace("?", "{%}", $string);
  // Convert the text into UTF-8.
  $string = mb_convert_encoding($string, "ISO-8859-1", "UTF-8");
  // Convert the text to ASCII.
  $string = mb_convert_encoding($string, "UTF-8", "ISO-8859-1");
  // Replace anything that is a question mark (left over from the conversion.
  $string = preg_replace('/(\s?\?\s?)/', ' ', $string);
  // Put back the .
  $string = str_replace("{%}", "?", $string);
  // Trim and return.
  return trim($string);
}

Use this simple function when you need to strip emojis from text.

Don't use this when for non latin script languages as it will strip out important characters from the text.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
7 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.