0

Can anyone explain why the input size doesn't match the length of the string it displays? And how I can fix this?

    <table>
<tr>
    <td>utf length<?php echo mb_strlen('hello', 'UTF-8'); ?>
        <input type="text" name="input" readonly value="hello" size="<?php echo mb_strlen('hello', 'UTF-8'); ?>">
    </td>
</tr>
<tr>
    <td>non utf lenth<?php echo strlen('hello'); ?>
        <input type="text" name="input" readonly value="hello" size="<?php echo strlen('hello'); ?>">
    </td>
</tr>
<tr>
    <td>utf length<?php echo mb_strlen('日本語', 'UTF-8'); ?>
        <input type="text" name="input" readonly value="日本語" size="<?php echo mb_strlen('日本語', 'UTF-8'); ?>">
</td>
</tr>
<tr>
    <td>non utf length<?php echo strlen('日本語'); ?>
        <input type="text" name="input" readonly value="日本語" size="<?php echo strlen('日本語'); ?>">
    </td>
</tr>
</table>

The only correctly displayed string is the mb_strlen('日本語', 'UTF-8'); All the other textboxes are too long.

Is there any way to have the all the textboxes behave so that they are exactly the length of the string they display?

anatak
  • 440
  • 2
  • 7
  • 16
  • 1
    The `size` attribute determines how many characters wide the field will be, but since every character in a proportional font may be a different width, the field will never quite match the exact width you want. See https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – kmoser Jun 04 '20 at 03:05

1 Answers1

0

The only correctly displayed string is the mb_strlen('日本語', 'UTF-8'); All the other textboxes are too long.

It is because as per the PHP Documentation,in case of mb_strlen() function we get to mention the encoding of the string and this function returns the encoded multi-byte character as one.Means in the length the encoded characters are taken as one whereas if strlen() used it counts the encoded character as multi-byte character(depends on the character you mention). And hence while using strlen() the string length becomes an issue.

As PHP Manual Says:(For mb_strlen())

Returns the number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

Kunal Raut
  • 2,495
  • 2
  • 9
  • 25