How to get the first character of string in PHP

by Lalita 07-Oct-19

0 84


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:

How to get the first character of string in PHP

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;
?>

How to get the first character of string in PHP

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;
?>

How to get the first character of string in PHP

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;
?>

How to get the first character of string in PHP


Share:


Comments

    Waiting for your comments

Leave a Reply