In PHP 8.1 & PHP 8.2, you can easily split the first 5 characters of a string using the substr() function. The substr() function allows you to extract a portion of a string based on a starting position and length.
Using substr() to Extract the First 5 Characters
The substr() function takes three parameters:
String: The input string.
Start Position: The position to start extracting from (0-based index).
Length: The number of characters to extract.
Here’s how you can use it to get the first 5 characters:
<?php $string = "HelloWorld"; $firstFiveChars = substr($string, 0, 5); // Output: "Hello" echo $firstFiveChars; ?>
Explanation
$string: The input string (“HelloWorld”).
0: The starting position (beginning of the string).
5: The number of characters to extract.