PHP Function of the Day (2011-9-14): substr

Hello again.

[fphp]substr[/fphp] returns a section of a string from another string. One of the most typical uses is to find the rest of the string after some flag character’s position in the string, which itself is found using [fphp]strpos[/fphp].

Here’s one application of the function from a larger class


protected function filterKeyName( $name ) {
	return stristr($name, self::DELIMITER) ?
		substr($name, strrpos($name, self::DELIMITER) + 1) :
		$name;
}

The delimiter constant is “_”. So, given “mypath_key” this function will return “key”. Given a string that doesn’t include the delimiter, the delimiter is returned directly. The +1 here assumes the delimiter is a single character - technically it should be strlen(self::DELIMITER) to not break if someone changes the delimiter to something with multiple characters.

Another example off PHP.net that returns the string between two other strings within a string using [fphp]substr[/fphp]


function get_between($input, $start, $end) {
  return substr( $input, strlen($start) + strpos( $input, $start ), ( strlen( $input ) - strpos( $input, $end) )*(-1) );
} 

Substr gets used a lot in string manipulation - Anyone else have some examples, comments, questions?

I think it’s important to point out to new users of substr that “start” and “length” can be (and often are) a negative integer - if Start is negative, then the substring begins that many characters from the end of the string…


$string = "quack.exe is a fun program";
echo substr($string,-4); //gram

and if length is negative, it leaves off that many characters.


$string = "quack.exe is a fun program";
echo substr($string,0,-4); //quack.exe is a fun pro

Ever wondered how your blog headlines give you a partial entry followed by … [Read More] ? Most likely, String Manipulation.