How to get the first character of string in PHP
0 11679
To get the first character of string in PHP, you can use a built in function i.e. substr(). But if you have special character in your string then it'll show a black question mark or other symbol rather than to show that special character as an output.
For example:
<?php $get_var = 'Äero hello'; $my_frst_char = substr($get_var, 0, 1); echo $my_frst_char; ?>
Output:
So this function is not always useful in this type of cases. Now to get first character can use another function string function which is also a built-in function i.e. mb_substr() function.
There are four parameters used in this funtion.
mb_substr($string, $string_start, $string_length, $string_encode)
1. $string: The string where the character is to extract.
2. $string_start: get or start from the position of string
3. $string_length: Length of chracters you want to show
4. $string_encode: Use to encode the character
<?php $get_var = 'Äero hello'; $my_frst_char = mb_substr($get_var, 0, 1, "UTF-8"); echo $my_frst_char; ?>
You can also change the character length:
<?php $get_var = 'Äero hello'; $my_frst_char = mb_substr($get_var, 0, 2, "UTF-8"); echo $my_frst_char; ?>
Also you can get the character from different position:-
<?php $get_var = 'Äero hello'; $my_frst_char = mb_substr($get_var, 5, 2, "UTF-8"); echo $my_frst_char; ?>
Share:
Comments
Waiting for your comments