How do i get the first and last character of a string in php?
What is the simplest way of checking whether the first letter of a string Show asked Feb 17, 2011 at 11:38
1
answered Feb 17, 2011 at 11:39
The GiGThe GiG 2,5332 gold badges27 silver badges29 bronze badges 1
answered Feb 17, 2011 at 11:42
TNCTNC 5,3601 gold badge25 silver badges28 bronze badges 1 Or use substr to get the last character:
answered Feb 17, 2011 at 11:44
qbert220qbert220 10.9k3 gold badges29 silver badges31 bronze badges 0 In this article, we will find the last character of a string in PHP. The last character can be found using the following methods.
Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is “Akshit” Its length is 6, in zero-indexing, the value of (length-1) is 5 which is the character “t” The length can be found using the PHP strlen() method. The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters. Syntax: strlen($string) Example: PHP
Output: Last Character of string is : s Using substr() Method: The substr() is a built-in function in PHP that is used to extract a part of string. Syntax: substr(string_name, start_position, string_length_to_cut) Example: For example, if the string is “Akshit loves GeeksForGeeks”. The last character of the string is “s”. There are 2 ways to reach “s”. From the beginning “s” is at the 25th position. We can find the length of the string, then display “length-1”. This means we want to display part of the string using substr() method where the starting point is “length-1”. PHP
Output: From the end, “s” is at 1st position. We can display string from (-1) Last character of String is : s From end: “s” is at 1st position We can display string from “-1” PHP
Output Last character of String is: s NOTE: If you’re using multibyte character encodings like UTF-8, use mb_substr() instead of substr . How do I find the first and last character of a string?To get the first and last characters of a string, use the charAt() method, e.g. str. charAt(0) returns the first character, whereas str. charAt(str. length - 1) returns the last character of the string.
How do I get the last character of a string in PHP?The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.
How do you get the first character of a string in PHP?To get the first character from a string, we can use the substr() function by passing 0,1 as second and third arguments in PHP.
How do I get the first letter of a word in PHP?So you can easily use $i[0] to fetch first letter.
|