How to Split the First 5 Characters in String Using PHP 8.3 & PHP 8.4?

In PHP 8.3 and PHP 8.4, you can easily split the first 5 characters of a string using the substr() function. This function allows you to extract a portion of a string based on a starting position and length. Here’s how you can do it:

Using substr() to Extract the First 5 Characters

The substr() function is the most straightforward way to extract the first 5 characters of a string.

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.