You can get your result by simply use substr():
Syntax substr(string,start,length)
Example
<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>
Output :
Hello
You can use the substr
function like this:
echo substr($myStr, 0, 5);
The second argument to substr
is from what position what you want to start and third arguments is for how many characters you want to return.
Use substr()
:
$result = substr($myStr, 0, 5);
An alternative way to get only one character.
$str = 'abcdefghij';
echo $str{5};
I would particularly not use this, but for the purpose of education. We can use that to answer the question:
$newString = '';
for ($i = 0; $i < 5; $i++) {
$newString .= $str{$i};
}
echo $newString;
For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4
More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access
Source: Stackoverflow.com