In PHP, there are a few different ways to get the first character of a string. In this post, we’ll look at three different appraoches: substr(), string as array, and mb_substr().
$text = 'PHP can help you build dynamic web applications. It enables developers to create sophisticated online systems rapidly and easily.'; echo $text; //output: 'P' //use substr echo substr($text, 0, 1); //output: 'P' //use mb_substr $text = 'ê123ë'; echo mb_substr($text, 0, 1, "UTF-8"); //output: 'ê'
The substr() function takes two parameters: the string we want to extract from and the starting position of the substring. In our case, we want to start at position 0, which is the first character in the string. Therefore, the syntax we need to use is substr($string, 0, 1). This will return the first character of $string. If we want to get the first three characters, we would use substr($string, 0, 3) and so on.
The mb_substr() function is similar to substr(), but it works with multi-byte characters (like Chinese or Russian). This is important because some characters take up more than one byte and substr() will treat them as two separate characters. mb_substr() is also faster than substr().