Search code examples
phpjquerycodeigniter-2

Automatically insert certain special characters at specific locations in a string using php codeigniter


I have a text field to enter a code, and it structure is like 200-00-0000.

When I enter the code in text field I have to generate the hyphen symbol(-) while typing the code at the specific locations as shown in the example code.

I'am using the PHP codeigniter.


Solution

  • You can use the following code:

    <?php
        $data = '200000000';
        echo "".substr($data, 0, 3)."-".substr($data, 3, 3)."-".substr($data,6); // 200-000-0000
    ?>
    

    check the DEMO here.

    In case if you wants to create phone number format then you can use this as follows:

    <?php
        $data = '2000000000';
        echo "(".substr($data, 0, 3).") ".substr($data, 3, 3)."-".substr($data,6); // (200) 000-0000
    ?>
    

    DEMO for phone number format

    Now; In case if you wants to go with some js code then you can use that as follows:

    HTML CODE

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script>
    
    </head>
    <body>
    <input type='text' id='customtext' name='customtext' />
    </body>
    </html>
    

    JS CODE:

    $(window).load(function()
    {
       var phones = [{ "mask": "###-###-####"}, { "mask": "(###) ###-##############"}];
        $('#customtext').inputmask({ 
            mask: phones, 
            greedy: false, 
            definitions: { '#': { validator: "[0-9]", cardinality: 1}} });
    });
    

    JS DEMO LINK