PHP Strings Primer - Extracting Substrings
(Page 24 of 37 )
Many times we don't want to deal with an entire string. We may want to extract just a portion of it to work with or store into another string. The substr()' function provides us with this functionality. With it, we can extract any portion of a larger string that we wish. It accepts three parameters, the string to work with, a starting point, and a length. The length is optional, and if it is not specified 'substr()' will return the portion of the larger string from the start point to the end.
Now, let's take a look at a couple of simple examples so that we may understand how 'substr()' works.
<?php $mystring = 'Hello World!'; echo substr($mystring, 2); echo "<br />\n"; echo substr($mystring, 2, 3); echo "<br />\n"; echo substr($mystring, -4); echo "<br />\n"; ?> |
Output:
The first call to 'substr()' specifies a starting point of 2. Everything starts counting at zero, so the number 2 specifies the third character. The first call will return the portion of $mystring from the third character to the end of the string. In the second call, we have specified the length. This will limit the string that is returned to only 3 characters.
The last call to 'substr()' is a little different than the others. You will notice that we specified a negative number. This tells the function to start counting from the end of the string. In this case, the function will return the last four characters of the string. If we had specified a length, we could have limited the number of characters it returned.
Next: Counting Paragraphs >>
More Programming Basics Articles
More By Matt Wade