The PHP substr() function

 

This function is short for Substring. You can grab a number of character from a string with substr. For example, suppose you wanted to check if an email address ended in .com. You could grab the last few characters and check them with an if statement. The syntax for substr( ) is this:

substr( string, start, length )

So you provide the function with a string, then you have to tell PHP which character in the string to start at. The length is how many characters you want to grab. This is optional. If you miss it out, you'll grab all the characters to the end of the string.

Here's an example that checks an email address to see if ends in .com.

$email = "test@test.com";
$email_end = substr( $email, strlen($email) - 4 );

if ($email_end == ".com" ) {

print "ends in .com";

}
else {

print "doesn't end in .com";

}

Run the script and see which one prints out!

You can also start the search from the end of the string. In which case, provide a negative number. Try this new substr( ) line, in place of the one above:

$email_end = substr($email, -4, 4);

This time, we have a figure of minus four. This means "start 4 characters from the left of the end of the string. There's also a length number specified. This means "grab four characters from your starting position.

 

We'll look at some more string function in later section (date and time functions, and functions you can use for security purposes). But for now, let's take a closer look at what functions are, and how you can create your own in PHP.

<-- Back One Page | Move on to the Next Part -->

Back to the PHP Contents Page