PHP - Slicing Strings

1
5K

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
Search
Categories
Read More
Other
الثورة البلوكتشين وتحولاتها في الصناعات المختلفة
مقدمة: شهدت تقنية البلوكتشين ثورة هائلة في السنوات الأخيرة، حيث أصبحت لديها القدرة على تغيير...
By MOHAMED ATTALLAH 2024-05-14 14:03:03 0 5K
Other
PHP echo and print Statements
With PHP, there are two basic ways to get output: echo and print. In this...
By PHP Tutorial 2024-05-17 07:20:06 0 5K
Other
PHP Break
The break statement can be used to jump out of different kind of loops. Break in For...
By PHP Tutorial 2024-05-17 07:50:37 0 4K
Other
PHP if...else Statements
PHP - The if...else Statement The if...else statement executes some code if a...
By PHP Tutorial 2024-05-17 07:46:12 0 3K
Other
PHP Operators
PHP Operators Operators are used to perform operations on variables and values. PHP divides the...
By PHP Tutorial 2024-05-17 07:41:39 0 6K