PHP substr() Tutorial 🎯

beginner
23 min

PHP substr() Tutorial 🎯

Welcome to our comprehensive PHP substr() tutorial! In this lesson, we'll learn how to use the substr() function, one of the essential PHP string functions, to manipulate and extract substrings from larger strings. Let's dive in!

Understanding the substr() Function πŸ“

The substr() function in PHP is used to extract a portion of a string. It takes two required parameters: the string you want to extract from ($str), and the starting position ($start). Optionally, it can also take a third parameter, the length of the substring you want to extract ($length).

php
$str = "Hello, World!"; $subStr = substr($str, 7); // Output: World!

πŸ’‘ Pro Tip: By default, the $length parameter is set to the end of the string if not provided.

The substr() Function with the Length Parameter πŸ’‘

If you want to extract a specific length of a substring instead of extracting from the start position to the end, you can include the length parameter.

php
$str = "Hello, World!"; $subStr = substr($str, 0, 5); // Output: Hello

The substr() Function with a Negative Start Position πŸ’‘

The substr() function allows you to start counting from the end of the string when using a negative value for the $start parameter.

php
$str = "Hello, World!"; $subStr = substr($str, -5); // Output: !

Real-World Examples πŸ’‘

Here are two practical examples that demonstrate the usefulness of the substr() function in PHP:

  1. Extracting the domain name from a URL:
php
$url = "https://www.codeyourcraft.com"; $domain = substr($url, strrchr($url, '/') + 1); // Output: codeyourcraft.com
  1. Extracting the first name from a full name:
php
$name = "John Doe"; $firstName = substr($name, 0, strpos($name, ' ')); // Output: John
Quick Quiz
Question 1 of 1

What does the substr() function do in PHP?

Quick Quiz
Question 1 of 1

What is the default value for the length parameter in the substr() function if not provided?

Quick Quiz
Question 1 of 1

How to extract the substring from the end of a string in PHP?