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!
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).
$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.
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.
$str = "Hello, World!";
$subStr = substr($str, 0, 5); // Output: HelloThe substr() function allows you to start counting from the end of the string when using a negative value for the $start parameter.
$str = "Hello, World!";
$subStr = substr($str, -5); // Output: !Here are two practical examples that demonstrate the usefulness of the substr() function in PHP:
$url = "https://www.codeyourcraft.com";
$domain = substr($url, strrchr($url, '/') + 1);
// Output: codeyourcraft.com$name = "John Doe";
$firstName = substr($name, 0, strpos($name, ' '));
// Output: JohnWhat does the substr() function do in PHP?
What is the default value for the length parameter in the substr() function if not provided?
How to extract the substring from the end of a string in PHP?