Extra Options Using substr()

Here you can see some more examples of using the substr() function in PHP to select part of a string.

The first parameter should be a string. In the examples below, this is $string = "Home sweet home";.

The second parameter is called an offset.
It specifies the index position of the first character you want.
(Remember that index numbers start at 0 not 1).
The rest of the string after this character is returned.
Spaces are treated as a character.

<?= substr($string, 1) ?>ome sweet home
<?= substr($string, 5) ?>sweet home

If the offset uses a negative number, it counts that number of characters from the end of the string and returns the rest.

<?= substr($string, -1) ?>e
<?= substr($string, -4) ?>home

The third parameter is the length parameter.
It indicates how many characters to return after the offset.

<?= substr($string, 0, 7) ?>Home sw
<?= substr($string, 5, 8) ?>sweet ho

When the offset is a negative number, the length still specifies how many characters to return after the position specified in the offset.

<?= substr($string, -10, 5) ?>sweet
<?= substr($string, -10, 8) ?>sweet ho

If the length is a negative value, that many characters are omitted from the end of the string.

<?= substr($string, 0, -5) ?>Home sweet
<?= substr($string, 5, -3) ?>sweet h