String Slicing

String slicing allows you to extract a portion of a string.

It takes two parameters: the starting index and the ending index (optional). It returns a new string containing the extracted portion.

Let's perform such operations on the string "computer". It's structure is the following:

string-slicing-structure

Two arguments slicing

Positive second argument slicing

Output:

In this example substr($str, 3) skips the first 3 symbols of the string - c, o, and m.

The other part of the string (starting from the 3rd index - p) is extracted - substr($str, 3);.

Negative third argument slicing

Negative indexes track the string characters in reverse.

positive-and-negative-argument-slicing

Output:

In this example substr($str, -3) extracts only the last 3 symbols of the string - t, e, and r.

Three arguments slicing

Positive arguments slicing

If the third argument is a positive number, it specifies how many symbols must be taken.

Output:

In this example substr($str, 3, 2) skips the first 3 symbols of the string - c, o, and m.

Afterwards, it takes 2 symbols - p and u.

Negative arguments slicing

If the third argument is a negative number, it specifies which should be the end negative index.

Output:

In this example substr($str, -5, -2) starts slicing at 5th symbol counting backwards and ends before the second symbol counting backwards.

Mixed arguments slicing

Both positive and negative arguments can be specified.

Output:

In this example substr($str, 1, -1) starts after the first symbol and ends before the last symbol.

Invalid cases

An invalid case simply returns an empty string. In such cases the slicing start argument position is after the slicing end.

Example of valid and invalid case:

Output:

Another invalid slicing case is specifying starting argument that's beyound the string's bounds:

Output: