PHP strings - substr() function

substr() is an usefull function to easily manipulate strings and use them, it returns a custom segment of a whole string.

substr, from position $n to end:
You can extract a small segment from a string from a position $n to the end:
<?php
$part = substr("I'm in Europe now",
7 ); // $part = "Europe now"
?>
Note: position counting start from position 0 !

substr, from position $n1 to $n2 :
You can choose, in substr() parameters, how many characters to extract after the position $n:
<?php
$part = substr("I'm in Europe now",
7 , 6 ); // $part = "Europe"
$part = substr("I'm in Europe now", 7 , 3 ); // $part = "Eur"
?>
Extract $n characters from the end of the string:
You can output the $n last character from a string:
<?php
$part = substr("I'm in Europe now",
-3 ); // $part = "now"
?>
Negatif parameters...

You may choose the start position with a negatif number, from the end of the string ( like we see in the previous code):
<?php
$part = substr("I'm in Europe now",
-3 ); // $part = "now"
$part = substr("I'm in Europe now", -3 , 2 ); // $part = "no"
?>
If te lenth parameter is negatif, it will count the end of the extracted string from the end...
<?php
$part = substr("I'm in Europe now", 7 , -4 ); // $part = "Europe"
?>
7 is the position whare the extraction should start, and -4 is the ending position counting from the end, so the fourth position from the end is the "e" character...

1 comments:

Diablo 3 Gold said...


Great article. that is my personal first holiday to your website. Many thanks for putting up a very good report.
D3 Gold


Cheap RS Gold