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.

Download  Run Code

 
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.

Download Code

That’s all about extracting the first n characters from a string in PHP.