How to extract the length of a string in PHP

In PHP, you can use the substr() function to extract a specific length of a string. This function takes three parameters: the string to extract from, the starting position, and the length to extract. Here is an example:

$str = "Hello World!";
$length = 5;

$substring = substr($str, 0, $length);

echo $substring; // 输出 "Hello"

In the example above, the variable $str is the string to be trimmed, and $length is the length to trim. The first parameter of the substr() function is the string to be trimmed, the second parameter is the starting position, and the third parameter is the length to be trimmed. Finally, use the echo statement to output the trimmed string.

It’s important to note that if the specified length exceeds the actual length of the string, the entire string will be returned. If the starting position is negative, the counting will begin from the end of the string.

bannerAds