Open In App

PHP mb_encode_numericentity() Function

The mb_encode_numericentity() function is an inbuilt function in PHP that is used to convert characters in a given string to their corresponding HTML numeric entity representations.

Syntax

mb_encode_numericentity(
    string $string,
    array $map,
    ?string $encoding = null,
    bool $hex = false
): string

Parameters

This function accepts four parameters that are described below.



Return Value

The mb_encode_numericentity() function returns the encoded string if the function successfully executes otherwise. It will return false.

Program 1: The following program demonstrates the mb_encode_numericentity() function.






<?php
  
$input_string = "Bonjour tout le monde! Ça va bien ?";
  
// Check if the input string contains french characters
if (preg_match("/[\x{00C0}-\x{02AF}]/u", $input_string)) {
    $convmap = [0x80, 0x10ffff, 0, 0x7fffffff];
    
    // Encode characters from decimal
   // (hexadecimal 0x80 to 0x10FFFF)
    $encoded_string = mb_encode_numericentity(
        $input_string,
        $convmap,
        "UTF-8",
        true
    );
} else {
    $encoded_string = $input_string;
}
echo $encoded_string;
?>

Output
Bonjour tout le monde! &#xC7;a va bien ?

Program 2: The following program demonstrates the mb_encode_numericentity() function.




<?php
$input_string = "Hello, こんにちは!";
  
// Encode characters from decimal 128 to 65535
$convmap = [0x80, 0xffff, 0, 0xffff];
$encoded_string
      mb_encode_numericentity($input_string, $convmap, "UTF-8");
echo $encoded_string;
?>

Output:

Hello, こんにちは!

Reference: https://www.php.net/manual/en/function.mb-encode-numericentity.php


Article Tags :