PHP Strings Extracting Substrings - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Strings Extracting Substrings - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Tuesday, May 7, 2019

PHP Strings Extracting Substrings


PHP Strings




Extracting Substrings


Problem

You want to extract part of a string, starting at a particular place in the string. For example, you want the first eight characters of a username entered into a form.

Solution

Example  Extracting a substring with substr( )

         $substring = substr($string,$start,$length);

         $username = substr($_GET['username'],0,8);


Discussion

If $start and $length are positive, substr() returns $length characters in the string, starting at $start. The first character in the string is at position 0.


Example  Using substr( ) with positive $start and $length

         print substr('watch out for that tree',6,5);

Example   prints:

         out f

If you leave out $length, substr() returns the string from $start to the end of theoriginal string

Example  Using substr( ) with positive start and no length

         print substr('watch out for that tree',17);

Example  prints:

         t tree

If $start is bigger than the length of the string, substr() returns false. If $start plus $length goes past the end of the string, substr() returns all of the stringfrom $start forward

Example  Using substr( ) with length past the end of the string

         print substr('watch out for that tree',20,5);

Example  prints:

         ree

If $start is negative, substr() counts back from the end of the string to determine
where your substring starts

Example  Using substr( ) with negative start

         print substr('watch out for that tree',-6);
         print substr('watch out for that tree',-17,5);

Example  prints:

         t tree
        out f

With a negative $start value that goes past the beginning of the string (for example, if
$start is −27 with a 20-character string), substr() behaves as if $start is 0. If $length is negative, substr() counts back from the end of the string to determine
where your substring ends

Example  Using substr( ) with negative length

        print substr('watch out for that tree',15,-2);
        print substr('watch out for that tree',-4,-1);

Example  prints:

        hat tr
       tre

No comments:

Post a Comment

Post Top Ad