PHP - Slicing Strings

1
7 الف

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
البحث
الأقسام
إقرأ المزيد
أخرى
PHP Associative Arrays
PHP Associative Arrays Associative arrays are arrays that use named keys that you assign to...
بواسطة PHP Tutorial 2024-05-17 08:01:14 0 7 الف
أخرى
PHP while Loop
The while loop - Loops through a block of code as long as the specified condition is...
بواسطة PHP Tutorial 2024-05-17 07:48:58 0 3 الف
أخرى
PHP Magic Constants
PHP Predefined Constants PHP has nine predefined constants that change value depending on where...
بواسطة PHP Tutorial 2024-05-17 07:40:16 0 4 الف
أخرى
PHP Numbers
In this chapter we will look in depth into Integers, Floats, and Number Strings. PHP Numbers...
بواسطة PHP Tutorial 2024-05-17 07:37:05 0 5 الف
أخرى
PHP Math
PHP has a set of math functions that allows you to perform mathematical tasks on numbers. PHP...
بواسطة PHP Tutorial 2024-05-17 07:39:09 0 5 الف