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
Rechercher
Catégories
Lire la suite
Autre
PHP $GLOBALS
$GLOBALS is an array that contains all global variables. Global Variables Global...
Par PHP Tutorial 2024-05-17 08:08:27 0 7KB
Autre
PHP Variables Scope
PHP Variables Scope In PHP, variables can be declared anywhere in the script. The scope of a...
Par PHP Tutorial 2024-05-17 07:18:52 0 10KB
Autre
PHP Multiline Comments
Multi-line Comments Multi-line comments start with /* and end with */. Any text...
Par PHP Tutorial 2024-05-17 07:15:48 0 6KB
Autre
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the browser....
Par PHP Tutorial 2024-05-17 07:10:53 0 8KB
Autre
PHP Loops
In the following chapters you will learn how to repeat code by using loops in PHP. PHP Loops...
Par PHP Tutorial 2024-05-17 07:48:35 0 4KB
Sociallez https://sociallez.com