PHP is one of the most popular programming languages used to develop web applications and APIs. Linux is the system of choice for serving up your PHP code and is also an ideal PHP development environment.
The PHP substr function takes a string (a series of characters) and returns only the specified portion of it.
substr ( $string , $start [, $length ] )
- The function returns either the specified portion of the given $string (even if it’s empty) as a new string or FALSE if the operation failed due to bad input
- $start is a positive integer and is the index (position) you want to start reading from
- It’s an index, so the first position is 0, the second is 1, etc
- $length is optional and will specify how many characters to read from $start
- If $length is not present, the entire rest of the string following the $start position will be returned
In this example, we take a sentence, and extract some data from it using substr():
$sentence = "The cat is orange"; $colour = substr($sentence, 11, 6); // "orange" $animal = substr($sentence, 4, 3); // "cat"
- The results of the substring operations are stored in the variables $colour and $animal
- Again, indexes start at 0 – but $length does not! $length should be the total number of characters we want to read from $string – in this case, the length of the word we are extracting
You can also provide negative integers to $start and $length:
$sentence = "The cat is orange"; $colour = substr($sentence, -6, 6); // "orange" $animal = substr($sentence, 4, -10); // "cat"
- If $start is negative, the start position will be calculated working backward from the end of the string
- This can be seen above – we start 6 characters from the end, and take a length of 6 characters, giving us “orange”
- If $length is negative, rather than counting how many characters to keep the given number of characters will instead be omitted from the end of the string.
- This is evident above as the ‘t’ in ‘cat’ is 10 characters from the end, so everything after that has been omitted, as the $length was given as -10
The substr() function is usually used when displaying values or processing user input. For example, you may wish to shorten a user-inputted value so it fits in a database column, or hide a portion of a value to protect a user’s identity.
Click here for more great PHP tutorials from LinuxScrew!
To view the official documentation for PHP substr() function: