Simple trick to extract substrings from a string

Simple trick to extract substrings from a string

Sometimes we need to extract a substring from a long string. Php provide a very flexible and powerful substr()function that allows you to extract a substring from a larger string.

It takes three parameters: the string to be worked on, a starting index and an optional length. The starting index can be specified as either a positive integer that means the index of a character in the string starting from the beginning or a negative integer means the index of a character starting from the end.

Here goes few simples of substr() function:

 

$my_string = "1234567";
echo substr ($my_string, 0, 3); // outputs 123
echo substr ($my_string, 1, 1); // outputs 2
echo substr ($my_string, -2); // outputs 67
echo substr ($my_string, 1); // outputs 234567
echo substr ($my_string, -2, 1); // outputs 6

 

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Share It

Related Posts