[PHP] Convert to half-width numbers and check if they are numbers
Sep 9, 2020
PHP
for beginners
The function used this time is `` mb_convert_kana``
For example, suppose it is described as follows
$ age = 20; // ← half-width numbers
if (is_numeric ($ age)) {
print ($ age.'Year');
} else {
print ('* Age is not a number');
}
The display is as follows
20-year-old
With the function is_numeric
You can check if the specified parameter is a number.
In the above example, ($ age) is checked.
If $ age ='aiueo'
* Age is not a number
Will be displayed.
Also, if you set $ age = '20'
(double-byte number) instead of $ age = '20'
,
In the same way, “* Age is not a number” is displayed.
Even if the user has to enter in half-width characters as above, It is often the case that you accidentally enter full-width characters.
Therefore, even if you enter a full-width number, you can write it so that it will be converted to a half-width number.
As mentioned at the beginning, the function mb_convert_kana
is used there.
If you write the code first, it will be as follows.
$ age = 20; // ← full-width numbers
$ age = mb_convert_kana ($ age,'n','UTF-8');
if (is_numeric ($ age)) {
print ($ age.'Year');
} else {
print ('* Age is not a number');
}
Even though ** 20 ** is entered as a full-width number, it is displayed as follows.
20-year-old
Describes mb_convert_kana
** mb ** → Abbreviation for multibyte, a word used when dealing with full-width characters such as Japanese
** convert_kana ** → Function to convert various kana
Various conversions can be performed depending on the parameters,
Here, it is possible to specify that it is converted to a half-width number by setting it to 'n'
.
'UTF-8'
specifies the character code used.
In the above code, ** 20 ** is a full-width number, but thanks to “**‘n’ **”, it is corrected to a half-width number. Therefore, it will be recognized as a numerical value and displayed as ** 20 years old **.
that’s all. Thank you for your hard work.