SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,026
    Mentioned
    64 Post(s)
    Tagged
    0 Thread(s)

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

    Hello again.

    substr 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 strpos.

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

    Code php:
    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 substr

    Code php:
    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?

  2. #2
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    71 Post(s)
    Tagged
    0 Thread(s)
    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...
    PHP Code:
    $string "quack.exe is a fun program";
    echo 
    substr($string,-4); //gram 
    and if length is negative, it leaves off that many characters.

    PHP Code:
    $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.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •