Advertisement

Google Ad Slot: content-top

PHP Slicing Strings

~1 min read · PHP
On this page

You can extract a portion of a string by using the substr() function.

Specify the start index and the number of characters you want to return.


Syntax:


substr(string $string, int $start, int $length = ?);


$string: The input string.

$start: The starting position to slice. A positive number counts from the beginning (0-indexed). A negative number counts from the end of the string.

$length (optional): The length of the substring to extract. If not provided, it extracts from $start to the end of the string. A negative value of $length will exclude characters from the end.

Example
Try it yourself

Note

The first character has index 0.

Slice to the End


By leaving out the length parameter, the range will go to the end:

Example
Try it yourself

Slice From the End


Use negative indexes to start the slice from the end of the string:

Example
Try it yourself

Note

The last character has index -1.


Negative Length


When you pass a negative length value, it will exclude that many characters from the end of the string:

Example
Try it yourself

In this case:

  • 0 means start from the beginning of the string.
  • -6 means exclude the last 6 characters, so "Hello, " is returned.