Extract first n characters from a string in PHP
This article demonstrates how to extract the first n characters from a string in PHP.
The standard solution to extract characters from the beginning of a string is using the substr() function. The second argument to substr() is offset, indicating the starting position, and the third argument is length, indicating the total number of characters to consider beginning from the offset. The substr() function returns the part of a string as specified by the offset and length parameters. To extract the first n characters from a single-byte character string (such as the ASCII character set), you can invoke substr() with offset 0 and length n.
|
1 2 3 4 5 6 7 8 9 |
<?php $string = 'Hello, Techie'; $n = 5; $first_n = substr($string, 0, $n); echo $first_n; // prints Hello ?> |
You can use the substr() function for an 8-bit, single-byte character set (SBCS). It is sufficient to represent the English character set, and the character sets for many European languages. However, for multibyte-character set (MBCS) encoding, such as Japanese and Chinese, you can use the mb_substr() function. This is because the multibyte strings can additionally include 2-byte characters, which cannot be represented using a single-byte character set.
|
1 2 3 4 5 6 7 |
<?php $string = 'サンプルテキスト'; $n = 4; $first_n = mb_substr($string, 0, $n, 'UTF-8'); echo $first_n; // prints サンプル ?> |
That’s all about extracting the first n characters from a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)