I need to get the first character of the given string. here i have a name in the session variable. i am passing the variable value to the substr
to get the first character of the string. but i couldn't.
i want to get the first character of that string.
for example John doe. i want to get the first character of the string j
. how can i get it using php?
<?php
$username = $_SESSION['my_name'];
$fstchar = substr($username, -1);
?>
In PHP to remove characters from beginning we can use ltrim but in that we have to define what we want to remove from a string i.e. removing characters are to be known. $str = "geeks" ; // Or we can write ltrim($str, $str[0]); $str = ltrim( $str , 'g' );
Method 1: Using String.The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .
You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.
To get the first n characters of a string, we can use the built-in substr() function in PHP. Here is an example, that gets the first 3 characters from a following string: <? php echo substr("Google", 0, 3); ?>
substr($username, 0, 1);
This will get you the first character
Another way is to do this:
$username[0];
mb_substr
: It takes into considetation the text encoding.mb_substr($str, 0, 1)
substr
substr($str, 0, 1)
$str[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With