Home > Enterprise >  AutoConvert Bengali Number to English Number while typing in PHP Form
AutoConvert Bengali Number to English Number while typing in PHP Form

Time:01-16

In Input form, How I can make an input box where.. When a user tries to input the Bengali Number and It will automatically convert it to English Number?

Suppose the input box is look like below:

<input type="text" name="number" size="45"/> Ex: If user typing ১২৩৪৫৬৭৮৯০ in the input box, it will convert to 1234567890 automatically. How to do that!!!

I tried it lots of time to fix but I cannot do it. I think the community will help me. Advance thanks!!!

CodePudding user response:

If you need this while the user is tying, you're looking for a JavaScript solution. If you need this on the backend, working with unicode is a bit more complicated for PHP since a lot of the built-in functions aren't designed for working with unicode, so you'd need to reach for the mb_* functions and need the mbstring extension enabled. There's probably ways to do this without on the PHP side. But I'd suggest doing this just in JavaScript. The amount of hoops you'd need to jump through to get this working on the PHP side isn't worth it. But I've attached both a frontend and backend solution so you can choose which you need. You can also combine these solutions such as if the user has JavaScript disabled, or an old browser etc.

<!doctype html>
<html lang="en">
<head>
    <script>
        function range(start, stop) {
            let result = [];
            for (let idx = start.charCodeAt(0), end = stop.charCodeAt(0); idx <= end; idx  ) {
                result.push(String.fromCharCode(idx));
            }
            return result;
        }
        function replaceBengaliNumeralsToArabicNumerals(str) {
            const zero = "\u09E6";
            const nine = "\u09EF";
            const chars = range(zero, nine).join('');
            return str.replace(/[\u09E6-\u09EF]/g, d => chars.indexOf(d));
        }
    </script>
</head>
<body>
<!-- blank action in HTML5 means submits to self -->
<form method="POST">
<p><input type="text" name="number" size="45"></p>
<p>Copy from here into the text box: &#x9E6;&#x9E7;&#x9E8;&#x9E9;&#x9EA;&#x9EB;&#x9EC;&#x9ED;&#x9EE;&#x9EF;</p>
<script>
    const el = document.querySelector('input[name=number]');
    ['keyup','keydown','keypress','change','click','dblclick','mousedown','mouseup','input','paste'].forEach(function(ev){
        el.addEventListener(ev, function(){
            el.value = replaceBengaliNumeralsToArabicNumerals(el.value);
        }, false);
    })
</script>
<p>Here's another text box, but without the JavaScript events so you can do this on the backend</p>
<p><input type="text" name="number2" size="45"></p>

<p style="margin-top:50px"><button type="submit">Submit</button></p>
</form>


<?php
if(!empty($_POST)) {

    // using a switch, so we can "break" without invoking "exit".
    // Invoking exit is bad since it affects code flow and prevents you from running stuff afterwards.
    // Another approach is to put this into a function and use return etc.
    switch(true) {
        default:
            // Validation and security check to prevent errors with unexpected input types
            if (!isset($_POST['number'])) {
                echo 'Missing name=number field.';
                break;
            }
            if (!isset($_POST['number2'])) {
                echo 'Missing name=number2 field.';
                break;
            }
            // security check to prevent errors with unexpected input types
            if (is_array($_POST['number'])) {
                echo 'Unexpected array field: name=number.';
                break;
            }
            if (is_array($_POST['number2'])) {
                echo 'Unexpected array field: name=number2.';
                break;
            }

            if ($_POST['number'] === '' && $_POST['number2'] === '') {
                echo 'Blank input was given. Please enter something into one of the text boxes';
                break;
            }

            $n = $_POST['number'];
            $n2 = $_POST['number2'];
            echo "<pre>\n";
            echo "Original Input:\n";
            echo "first field: " . htmlentities($n) . "\n";
            echo "second field: " . htmlentities($n2) . "\n";
            echo "\n";
            echo "After filtering in PHP:\n";
            // credit for strtr_utf8: https://stackoverflow.com/questions/1454401/how-do-i-do-a-strtr-on-utf-8-in-php
            function strtr_utf8($str, $from, $to) {
                $keys = array();
                $values = array();
                preg_match_all('/./u', $from, $keys);
                preg_match_all('/./u', $to, $values);
                $mapping = array_combine($keys[0], $values[0]);
                return strtr($str, $mapping);
            }
            // credit for mb_range: https://gist.github.com/rodneyrehm/1306118
            mb_internal_encoding('UTF-8');
            function mb_range($start, $end) {
                // if start and end are the same, well, there's nothing to do
                if ($start == $end) {
                    return array($start);
                }

                $_result = array();
                // get unicodes of start and end
                list(, $_start, $_end) = unpack("N*", mb_convert_encoding($start . $end, "UTF-32BE", "UTF-8"));
                // determine movement direction
                $_offset = $_start < $_end ? 1 : -1;
                $_current = $_start;
                while ($_current != $_end) {
                    $_result[] = mb_convert_encoding(pack("N*", $_current), "UTF-8", "UTF-32BE");
                    $_current  = $_offset;
                }
                $_result[] = $end;
                return $_result;
            }
            function replaceBengaliNumeralsToArabicNumerals($str)
            {
                return strtr_utf8($str, implode('',mb_range("\u{09E6}", "\u{09EF}")), implode('',range(0,9)));
            }

            $replaced_n = replaceBengaliNumeralsToArabicNumerals($n);
            $replaced_n2 = replaceBengaliNumeralsToArabicNumerals($n2);
            echo "first field:" . htmlentities($replaced_n) . "\n";
            echo "second field:" . htmlentities($replaced_n2) . "\n";
            echo "<pre>";
    }
}

?>
</body>
</html>

I suppose we could also include Eastern Arab Numerals:

let numbers = {
    '০': 0,
    '১': 1,
    '২': 2,
    '৩': 3,
    '৪': 4,
    '৫': 5,
    '৬': 6,
    '৭': 7,
    '৮': 8,
    '৯': 9,
    '           
  • Related