There are many string functions that come in so useful with PHP work. All of the string functions can be found in the
PHP Manual however I'll cover the two I use the most below, and then obviously others as time goes on.
substr() – This returns a section of the string which you control with the start and length or end values. This is handy if
you just want to display a short excerpt of a longer description. There are many uses of this but without going into too
much detail they won't necessarily make sense at present.
For using the function you have several options:
1. substr("abcdef", 2) – this would output 'cdef' ie. it outputs everything after the first 2 characters.
2. substr("abcdef", 1, 3) – this would output 'bcd' ie. the pointer starts at position 1 (bearing in mind the letter 'a' is
currently in position 0) and then print 3 characters.
3. substr("abcdef", 0, -1) – this would output 'abcde' ie. the pointer starts at position 0 and outputs all until the pointer
is minus one character from the end.
4. substr("abcdef", -2) – this would output 'ef' ie. the last two characters regardless of knowing the length of the string
str_replace() – This takes an existing character or string, along with the replacement string and searches the given string
for any existance of the string to replace. Okay that sounded confusing! Much easier with a few examples:
- Array Code
- str_replace("a", "b", "Mary had a little lamb"); // would produce 'Mbry hbd b little lbmb'
- str_replace(" & ", " & ", "You & I"); // would produce 'You & I' which is valid markup for XHTML Strict
- str_replace(" ", "%20", "http://www.domain.com/contact us.htm"); // unfortunately a lot of people believe that spaces in urls are fine to use when they really aren't. This is one way to clean them up in your links.
explode() – This allows you to choose a character in a string and split the string up into an array, where each bit in the
original string started and/or ended with the chosen character. For example
- Array Code
- $string = explode("-", "Item 1-Item 2-Item 3");
- // $string now contains 3 items
- print $string; // would give 'Item 1'
- print $string; // would give 'Item 2'
- print $string; // would give 'Item 3'
So those are the 3 functions I use day in day out. Mainly they're used on their own but at times can be combined to produce the desired output for a string.