Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

Slicing Strings

Slicing

You can extract a range of characters using the substr() function.

Specify the starting index and the number of characters you wish to return.

Example

Start the slice at index 6 and continue for 5 positions.

$x = "Hello World!";
echo substr($x, 6, 5);
Note: The first character is at index 0.

Slice to the End

By omitting the length parameter, the range will extend to the end of the string.

Example

Begin the slice at index 6 and continue to the end.

$x = "Hello World!";
echo substr($x, 6);

Slice From the End

Use negative indexes to initiate the slice from the end of the string.

Example

Retrieve the 3 characters starting from the “o” in “world” (index -5).

$x = "Hello World!";
echo substr($x, -5, 3);
Keep in mind that the last character has an index of -1.

Negative Length

Use a negative length to indicate how many characters to skip, beginning from the end of the string.

Example

From the string “Hi, how are you?”, extract the characters starting from index 5 and continue until the 3rd character from the end (index -3).

The result should be “ow are y”.

$x = "Hi, how are you?";
echo substr($x, 5, -3);