PHP - Slicing Strings

1
8KB

Slicing

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

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

ExampleGet your own PHP Server

Start the slice at index 6 and end the slice 5 positions later:

$x = "Hello World!";
echo substr($x, 6, 5);
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

Start the slice at index 6 and go all the way to the end:

$x = "Hello World!";
echo substr($x, 6);
Try it Yourself »

Slice From the End

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

Example

Get the 3 characters, starting from the "o" in world (index -5):

$x = "Hello World!";
echo substr($x, -5, 3);
Try it Yourself »

Note The last character has index -1.


Negative Length

Use negative length to specify how many characters to omit, starting from the end of the string:

Example

From the string "Hi, how are you?", get the characters starting from index 5, and continue until you reach the 3. character from the end (index -3).

Should end up with "ow are y":

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

Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.

 
 

 

 

Like
1
Pesquisar
Categorias
Leia mais
Outro
PHP Array Functions
PHP Array Functions PHP has a set of built-in functions that you can use on arrays....
Por PHP Tutorial 2024-05-17 08:07:42 1 8KB
Outro
PHP Create Arrays
Create Array You can create arrays by using the array() function: ExampleGet your...
Por PHP Tutorial 2024-05-17 08:01:55 0 8KB
Outro
PHP Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending or...
Por PHP Tutorial 2024-05-17 08:06:46 0 8KB
Outro
PHP Global Variables - Superglobals
Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available...
Por PHP Tutorial 2024-05-17 08:08:10 0 10KB
Outro
PHP - Escape Characters
Escape Character To insert characters that are illegal in a string, use an escape character. An...
Por PHP Tutorial 2024-05-17 07:32:36 0 11KB
Sociallez https://sociallez.com